range() is a built-in function that gives you an immutable sequence of numbers, and its most common job is making a loop run a set number of times.
The sequence belongs to a data type of its own, named range.
Note: Something immutable stays exactly as it was created; it cannot be modified later.
Creating ranges
You can pass range() 1, 2 or 3 arguments. The full syntax looks like this:
range(start, stop, step)
Call range() With One Argument
A single argument is treated as the stop value.
Leave out start, which is optional, and counting begins at 0 by default.
So range(10) produces the numbers 0 through 9: the start value 0 is included, while the stop value 10 is not.
x = range(10)
Call range() With Two Arguments
With two arguments, the first is the start value and the second is the stop value.
So range(3, 10) produces the numbers 3 through 9:
x = range(3, 10)
Call range() With Three Arguments
A third argument sets the step value.
The step is the gap between one number and the next. You can leave it out, and then it is 1 by default.
So range(3, 10, 2) counts from 3 up to 9 in steps of 2:
x = range(3, 10, 2)
Using ranges
A very common place to find a range is a for loop, which walks through its numbers one by one.
Example
Print each number in a range:
Output: complete Python program
for i in range(10):
print(i)
Using List to Display Ranges
A range object is its own immutable number sequence, and printing one does not list its numbers.
To see them, people usually turn the range into a list first.
Example
Turn a few different ranges into lists:
Output: complete Python program
print(list(range(5)))
print(list(range(1, 6)))
print(list(range(5, 20, 3)))
Slicing Ranges
As with other sequences, you can slice a range to pull out part of it.
Note: In this example, the first print shows the value at index 2, and the second shows a new range object covering indexes 0 to 3.
Example
Pull a piece out of a range:
Output: complete Python program
r = range(10)
print(r[2])
print(r[:3])
Membership Testing
The in operator lets you test whether a range contains a number.
You get True if the number is in the range and False if it isn't.
Example
Find out whether 6 and 7 belong to a range:
Output: complete Python program
r = range(0, 10, 2)
print(6 in r)
print(7 in r)
Length
Pass a range to the len() function and it tells you how many elements the range has.
Example
Count the elements of a range:
Output: complete Python program
r = range(0, 10, 2)
print(len(r))