range() in Python produces a sequence of integers that starts at 0 by default, goes up in steps of 1, and stops before the number you give it. for i in range(5) runs the loop body five times, with i set to 0, 1, 2, 3 and 4.
The examples below come from the Python 3 documentation. Output lines are example output.
The three forms of range()
The documentation gives two call signatures, which cover three ways to use it:
range(stop)
range(start, stop)
range(start, stop, step)
If you leave out start, it is 0. If you leave out step, it is 1. All arguments must be integers (or objects that implement __index__()), and they are positional only, so range(stop=5) is not valid.
| Call | Values produced |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(5, 10) | 5, 6, 7, 8, 9 |
range(0, 10, 3) | 0, 3, 6, 9 |
range(0, -10, -1) | 0, -1, -2, ... -9 |
range(-10, -100, -30) | -10, -40, -70 |
Why the stop value is excluded
The end point is never part of the sequence. This trips up most beginners: range(1, 10) ends at 9, not 10. To count from 1 to 10 you write range(1, 11).
The reason is practical. range(10) yields exactly 10 values, and they are the valid indices of a sequence with 10 items. It also makes ranges easy to join: range(0, 5) followed by range(5, 10) covers 0 to 9 with no gap and no overlap.
Using range() in a for loop
for i in range(5):
print(i)
Example output:
0
1
2
3
4
Use it when you need a counter or need to repeat something a fixed number of times. If you do not need the number itself, a common convention is to name the variable _:
for _ in range(3):
print("hello")
For loops that also need a condition inside them, see Python for loop with if condition. For a loop inside a loop, see nested for loops explained.
How to count down with a negative step
With a negative step, the sequence counts down, and the loop stops when the value would go to or past stop. Start must be larger than stop, or the result is empty.
for i in range(5, 0, -1):
print(i)
Example output:
5
4
3
2
1
Zero is not printed, because the stop value is excluded in this direction as well. To include 0, use range(5, -1, -1).
Step sizes: even numbers, multiples and every nth item
A step larger than 1 skips values. These are the usual patterns:
list(range(0, 30, 5)) # [0, 5, 10, 15, 20, 25]
list(range(2, 11, 2)) # [2, 4, 6, 8, 10]
list(range(1, 10, 2)) # [1, 3, 5, 7, 9]
The second line gives even numbers from 2 to 10, and the third gives odd numbers. Note that 10 appears in the second list only because the stop value is 11.
A step of 0 is an error. Python raises ValueError, since the sequence could never advance.
Why print(range(5)) shows range(0, 5)
In Python 3, range() does not build a list. Printing it shows the object itself:
>>> range(10)
range(0, 10)
To see the values, convert it to a list:
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The documentation explains the design: a range object always takes the same small amount of memory, however large the range is, because it stores only start, stop and step and calculates each item when needed. range(10) and range(10_000_000) are the same size in memory. You only pay for the values if you convert it to a list or tuple.
Because a range is iterable, you can pass it straight to functions that accept one:
>>> sum(range(4)) # 0 + 1 + 2 + 3
6
What else a range object can do
A range is a real sequence type, so it supports indexing, slicing, len(), the in operator and .index(). It does not support concatenation or repetition (+ and *), because the result would usually not follow a regular pattern.
>>> r = range(0, 20, 2)
>>> r
range(0, 20, 2)
>>> 10 in r
True
>>> 11 in r
False
>>> r.index(10)
5
>>> r[5]
10
>>> r[-1]
18
>>> r[:5]
range(0, 10, 2)
Slicing a range gives back another range, not a list. Membership tests with in on integers run in constant time rather than scanning every value, so x in range(0, 1_000_000) is cheap. A range also has read-only start, stop and step attributes.
Two ranges are equal when they represent the same values, even if their arguments differ. The documentation gives range(0, 3, 2) == range(0, 4, 2) as an example, since both produce 0 and 2.
range(len(...)) versus enumerate()
A frequent use of range() is to loop over the positions in a list:
names = ["Mary", "had", "a", "little", "lamb"]
for i in range(len(names)):
print(i, names[i])
This works, and the output pairs each index with its item. The tutorial itself adds that in most such cases enumerate() is more convenient, because it hands you the index and the item together:
for i, name in enumerate(names):
print(i, name)
Keep range(len(...)) for cases where you really need positions, for example to modify the list in place, or to compare each item with its neighbour using names[i + 1]. If you only need the items, loop over the list directly.
Common mistakes with range()
- Off by one at the end.
range(1, 10)stops at 9. Add 1 to the stop value to include it. - Floats as arguments.
range(0, 1, 0.1)is rejected, because the arguments must be integers. Generate the integers and divide:[x / 10 for x in range(0, 10)]. The list comprehension guide covers that syntax. The Python documentation also links a linspace recipe for evenly spaced floats. - Counting down without a negative step.
list(range(5, 0))returns[], because with the default step of 1 the first value already fails the stop condition. An empty range is not an error, so the loop body simply never runs. - Expecting a list. Code such as
range(5) + range(5)fails because ranges cannot be concatenated. Convert each to a list first:list(range(5)) + list(range(5)).
How an empty range is decided
The documentation defines the contents with a formula: item i is start + step * i, and items continue while they stay below stop for a positive step, or above stop for a negative step. If the very first item, start, already fails that test, the range is empty. That is why list(range(0)) and list(range(1, 0)) both give [].
The same formula explains reversed slices. Slicing a range with a negative step walks it backwards and returns another range, for instance range(0, 20, 2)[::-1] gives range(18, -2, -2) (example output). You can write the same thing with a negative step directly when you build the range, which is usually easier to read.
Frequently asked questions
- Does range() include the stop value?
- No. The stop value is never part of the sequence. range(5) produces 0, 1, 2, 3, 4, and range(1, 11) produces 1 through 10. The Python documentation notes that range(10) generates 10 values, which are the legal indices of a sequence of length 10.
- Is range() a list in Python 3?
- No. It returns a range object that behaves like an immutable sequence but stores only start, stop and step. It calculates each item when asked, so it uses the same small amount of memory however large the range is. Wrap it in list() when you need an actual list.
- Can range() use decimals or floats?
- No. The arguments must be integers, or objects that implement the __index__() method. For evenly spaced decimal values, build them with a list comprehension, for example [x / 10 for x in range(0, 11)], or use a library such as NumPy.
- What happens if the step is 0?
- Python raises a ValueError, because a step of zero could never move from start to stop. Use a positive step to count up and a negative step to count down.
- How do I loop over a range backwards?
- Give range() a negative step and a start that is larger than the stop. range(5, 0, -1) produces 5, 4, 3, 2, 1. Remember that the stop value is still excluded, so use range(5, -1, -1) if you want to include 0.