Python range(): Start, Stop and Step
range() produces integers that follow one after another. You mostly use it with for to say "repeat n times" or "from 1 to n". There is one rule that matters most: the stop value is not included.
range(stop)
range(start, stop)
range(start, stop, step)
range(n): from 0 to n-1
With a single number, the range starts at 0 and goes up to just before that number. So range(5) has five numbers (0, 1, 2, 3, 4), and you can use it as it is when you want to do the same thing five times.
print(list(range(5)))for i in range(3): print("hi", i)print(len(range(5)))[0, 1, 2, 3, 4] hi 0 hi 1 hi 2 5
Counting starts at 0 to match list indexes, which also start at 0. range(len(a)) gives every index of a.
Setting the start and stop
With two numbers, the range goes from start to stop - 1. For 1 to n, write range(1, n + 1). The count is always stop - start.
n = 5print(list(range(1, n + 1)))print(list(range(3, 7)))print(list(range(-2, 2)))print(len(range(3, 7)))[1, 2, 3, 4, 5] [3, 4, 5, 6] [-2, -1, 0, 1] 4
Using a step and counting backwards
The third number is the step. A negative step counts down. The stop value is still not included, so to go down to 0 you set the stop to -1.
print(list(range(0, 10, 3)))print(list(range(1, 10, 2)))print(list(range(10, 0, -2)))print(list(range(4, -1, -1)))print(list(reversed(range(5))))[0, 3, 6, 9] [1, 3, 5, 7, 9] [10, 8, 6, 4, 2] [4, 3, 2, 1, 0] [4, 3, 2, 1, 0]
The last two lines give the same result. If working out the stop value is confusing, reversed(range(n)) is easier to read.
A range is not a list
A range does not build all its numbers in advance. It only remembers the start, stop and step. So if you print it as it is, you get range(0, 5) instead of the numbers, and even a huge range uses almost no memory. Getting a value by index and asking whether a value is in it with in work just as they do for a list.
r = range(0, 20, 5)print(r)print(list(r))print(r[1], r[-1])print(15 in r, 7 in r)print(len(range(10**9)))range(0, 20, 5) [0, 5, 10, 15] 5 15 True False 1000000000
Convert with list(range(...)) only when you want the numbers as a list.
Common mistakes
Thinking the stop value is included
for i in range(1, 5):
print(i, end=" ")
print()
→ You expected 1 to 5 but got 1 2 3 4
The stop value is left out. To go up to 5, use range(1, 6). To go up to n, use range(1, n + 1).
Counting backwards without a step
print(list(range(5, 0)))
for i in range(5, 0):
print(i)
print("end")
→ There is no error. The range is empty, so the loop never runs
The default step is 1, so when the start is larger than the stop there is nowhere to go. Always give -1, as in range(5, 0, -1).
Passing the result of a division directly
n = 10
for i in range(n / 2):
print(i)
→ TypeError: 'float' object cannot be interpreted as an integer
/ gives a float (5.0) even when the division is exact. range only takes integers, so use floor division: range(n // 2). You can't make a range that goes up by 0.1 with range either.