The range() Function
By the end of this lesson you will be able to produce any run of whole numbers you need with range(): 1 to 100, every fifth year, a countdown, train departure times every 45 minutes, or the positions of items in a list. You will also understand what a range really is, which explains why it is so fast and uses almost no memory.
You met range() briefly in for Loops. This lesson goes into the details that cause off-by-one bugs, and the features most beginners never discover.
A range is a sequence of numbers
range() does not make a list. It makes a range object: a small object that remembers only three numbers, start, stop and step, and works out each number when it is needed. Think of a railway timetable that says "every 15 minutes from 6:00". You do not need the full printed list of times; the rule is enough to find any of them.
seats = range(1, 6)
print(seats)
print(type(seats))
print(list(seats))
print(len(range(0, 100, 5)))range(1, 6) <class 'range'> [1, 2, 3, 4, 5] 20
Printing a range shows the rule, not the numbers. To see the numbers, turn it into a list with list() or loop over it. len() works directly: there are 20 multiples of 5 from 0 up to (but not including) 100.
The three forms
range() can take one, two or three whole numbers:
| Call | Meaning | Numbers |
|---|---|---|
range(stop) | 0 up to stop | range(5): 0, 1, 2, 3, 4 |
range(start, stop) | start up to stop | range(2020, 2025): 2020 to 2024 |
range(start, stop, step) | jump by step | range(0, 31, 10): 0, 10, 20, 30 |
In every form, start is included and stop is not. Defaults are start=0 and step=1.
print(list(range(5)))
print(list(range(2020, 2027)))
print(list(range(0, 31, 5)))
print(list(range(10, 0, -1)))
print(list(range(10, 0)))
print(list(range(5, 5)))[0, 1, 2, 3, 4] [2020, 2021, 2022, 2023, 2024, 2025, 2026] [0, 5, 10, 15, 20, 25, 30] [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] [] []
Look at the last three lines:
range(10, 0, -1)counts down. A negative step walks downwards, and it still stops beforestop, so it ends at 1, not 0.range(10, 0)is empty. The default step is +1, and you cannot climb from 10 up to 0.range(5, 5)is empty too. There is nothing between a start and a stop that are equal.
An empty range is not an error. A for loop over it simply runs zero times, which is usually what you want.
Why stop is not included
Leaving out stop feels strange at first, but it makes everyday code simpler:
range(n)gives exactlynnumbers, andrange(a, b)givesb - anumbers.range(len(items))gives exactly the valid positions of a list, 0 tolen(items) - 1.- Two ranges join without overlap:
range(0, 5)thenrange(5, 10)covers 0 to 9 once.
This is the same rule as string slicing in String Indexing & Slicing. When you do need the last number, add 1 to it: range(1, 101) for 1 to 100. Here it is with train departures every 45 minutes from 6:00 to 9:00, both included:
first = 6 * 60
last = 9 * 60
for minutes in range(first, last + 1, 45):
hours, mins = divmod(minutes, 60)
print(f"{hours:02d}:{mins:02d}")06:00 06:45 07:30 08:15 09:00
Step by step: the times are turned into minutes after midnight (360 and 540), range() steps through them 45 at a time, and divmod() splits each value back into hours and minutes. Without the + 1, the 09:00 train would be missing.
Counting down
There are two ways to go backwards. Use whichever reads better:
for count in range(5, 0, -1):
print(count, end=" ")
print("Go!")
print(list(reversed(range(1, 6))))5 4 3 2 1 Go! [5, 4, 3, 2, 1]
With a negative step, start must be the bigger number, and stop is one past the last number you want, in the downward direction. reversed(range(1, 6)) lets you write the familiar "1 to 5" and simply walk it backwards, which is harder to get wrong.
Only whole numbers
range() works only with integers. Two mistakes give errors straight away:
for i in range(0, 10, 0):
print(i)ValueError: range() arg 3 must not be zerofor km in range(0, 2, 0.5):
print(km)TypeError: 'float' object cannot be interpreted as an integerA step of 0 would never move, so Python refuses it. For decimal steps, loop over whole numbers and divide: for i in range(5): print(i * 0.5) gives 0.0, 0.5, 1.0, 1.5 and 2.0. For money, count in paise (whole numbers) and convert to rupees only when you print.
A range is a real sequence
A range behaves like a read-only list. You can index it, slice it, ask its length, test membership, and loop over it as many times as you like.
evens = range(0, 1_000_000_000, 2)
print(len(evens))
print(evens[10], evens[-1])
print(evens[:5])
print(123456788 in evens, 7 in evens)
print(evens.index(100))
print(range(0, 3) == range(0, 3, 1))
small = range(3)
print(list(small), list(small))500000000 20 999999998 range(0, 10, 2) True False 50 True [0, 1, 2] [0, 1, 2]
Half a billion even numbers, and yet the range was created instantly. That is because it stores only its start, stop and step, so a huge range uses the same small amount of memory as a tiny one. Slicing a range gives another range. For whole numbers, in is worked out with arithmetic, not by checking every number, so it is fast even here. The last line shows that a range can be looped over again and again; it does not get "used up".
Positions in a list
Usually you loop over a list directly, or use enumerate() when you need positions. range(len(...)) is the right tool when you need to look at neighbouring items, such as comparing each match with the one before:
scores = [45, 62, 58, 80, 91]
for i in range(1, len(scores)):
change = scores[i] - scores[i - 1]
print(f"Match {i + 1}: {scores[i]} ({change:+d})")
print("Sum of 1 to 100:", sum(range(1, 101)))Match 2: 62 (+17) Match 3: 58 (-4) Match 4: 80 (+22) Match 5: 91 (+11) Sum of 1 to 100: 5050
The loop starts at position 1 because position 0 has no previous match. The +d format adds a plus sign to rises. sum() works on a range directly, with no list needed. Later you will learn itertools.pairwise(), a neater way to walk neighbouring pairs, in itertools & functools.
Common mistakes
- Forgetting that
stopis excluded.range(1, 10)ends at 9. For 1 to 10, writerange(1, 11). - Counting down without a negative step.
range(10, 1)is empty; writerange(10, 0, -1). - Passing a float.
range(0, 1, 0.1)raisesTypeError; use whole numbers and divide. - Printing a range and expecting numbers.
print(range(3))showsrange(0, 3); uselist(). - Using
range(len(...))everywhere. Loop over items directly or useenumerate()unless you need neighbours.
Interview questions
1. Is range a generator or a list?
Neither. It is an immutable sequence type. Unlike a list it does not store its numbers, and unlike a generator it supports len(), indexing, slicing and in, and can be looped over any number of times.
2. How much memory does range(10**9) use?
Very little, and the same as range(10). A range object stores only start, stop and step and calculates each value on demand. list(range(10**9)) would try to build a billion integers and likely run out of memory.
3. Why does range() leave out the stop value?
It makes counts and positions line up: range(n) has exactly n items, range(len(seq)) gives exactly the valid indexes, and consecutive ranges like range(0, 5) and range(5, 10) meet without overlap.
4. How do you loop from 10 down to 1?
for i in range(10, 0, -1): or for i in reversed(range(1, 11)):. With a negative step the stop is still excluded, so it must be 0 to include 1.
5. Can range() use decimal steps?
No. It accepts only integers and raises TypeError for floats, and ValueError for a step of 0. Loop over integers and scale them, for example i / 10.
Key points
range(start, stop, step)makes a lazy sequence of whole numbers;startis in,stopis out.- Defaults are
start=0andstep=1; a negative step counts down. - Ranges that cannot reach
stopare empty, and a loop over them runs zero times. - Only integers are allowed, and the step cannot be 0.
- A range supports
len(), indexing, slicing and fastin, and uses tiny memory at any size. - Add 1 to
stopwhen you need the last number included.
Exercise
A school in Jaipur numbers its roll calls from 1 to 40. Using range() only (no lists typed by hand), print: the roll numbers of students who sit in the front row, which is every 8th roll number starting at 1; a countdown from 10 to 1 on one line followed by "Exam starts!"; how many even roll numbers there are; and whether roll number 37 is odd by testing membership in a range of odd numbers. Finally, print bell times every 40 minutes from 8:00 to 13:20 inclusive in HH:MM format.
Show solution
front_row = range(1, 41, 8)
print("Front row:", list(front_row))
for n in range(10, 0, -1):
print(n, end=" ")
print("Exam starts!")
evens = range(2, 41, 2)
print("Even roll numbers:", len(evens))
odds = range(1, 41, 2)
print("37 is odd:", 37 in odds)
for minutes in range(8 * 60, 13 * 60 + 20 + 1, 40):
hours, mins = divmod(minutes, 60)
print(f"{hours:02d}:{mins:02d}", end=" ")
print()Front row: [1, 9, 17, 25, 33] 10 9 8 7 6 5 4 3 2 1 Exam starts! Even roll numbers: 20 37 is odd: True 08:00 08:40 09:20 10:00 10:40 11:20 12:00 12:40 13:20
Every range uses 41 as stop so that 40 can be included. The countdown needs the negative step with stop at 0. The bell times are minutes after midnight, with + 1 so the 13:20 bell is not lost, and divmod() turns them back into hours and minutes.
Quick Quiz
1. What does list(range(3, 12, 3)) give?
The step is 3 and the stop value 12 is excluded.
2. What does list(range(8, 2)) give?
With the default step of +1, you cannot climb from 8 to 2, so the range is empty.
3. What happens with range(0, 5, 0.5)?
range() accepts only integers; loop over whole numbers and divide instead.
4. Why can range(10**12) be created instantly?
A range is a lazy sequence; its memory use does not grow with its length.
Learn Python with a mentor
Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
