Key Terms
- Step-size
- A constant different between successive terms.
range() function
The range() function allows us to generate sequences of
numbers with the following syntax:
range(start, stop, step-size)
Here is a simple program that prints out the numbers 1 through 4 to the console. Note that last number printed is less than the stop number.
# Range function with a the default step-size of 1
for value in range(1,5):
print(value)
1
2
3
4
It is also possible to specify a step-size by supplying a third argument:
# Print all even numbers from 1-10
for value in range(1,11,2):
print(value)
1
3
5
7
9
list() Function
You can also make a range of numbers into a list by calling the
list() function. You can then use any of the list methods
such as sort() to manipulate your list.
# Make a list of numbers from 1-4
numbers = list(range(1,5))
print(numbers)
[1, 2, 3, 4]
You are not just limited to counting by an integer step-size. You can specify an expression to generate almost any sequences imaginable:
# Create an empty list
squares = []
# For loop to generate integers from 1 to 10
for value in range(1,11):
# Append the square of the integer in value to the List
squares.append(value**2)
# Print the list
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
You can use the min(),
max() and
sum() functions to get the
minimum,
maximum and
sum of all the numbers in a list
respectively
digits = [1,2,3,4,5,6,7,8,9,0]
# Find minimum, maximum and total sum of the digits list
print(min(digits))
print(max(digits))
print(sum(digits))
0
9
45
In a previous program, it took 3 lines to create a list of perfect square numbers but with a list comprehension you can do all three steps in one line.
# Build a list of the first 10 perfect square numbers
squares = [value**2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]