Beginner Chapter 65 · 25 min read · Module 5: Control Flow
range() Function
- After this chapter you can use range() with one, two or three arguments.
- You can predict the numbers that a range produces, including the excluded stop value.
- You can count backwards using a negative step.
- You can turn a range into a list and use len() and in on it.
- You can use range() to loop a fixed number of times or over list positions.
The range() function gives you a sequence of whole numbers. It is the usual partner of the for loop whenever you want to repeat something a fixed number of times or count through numbers such as 1 to 10.
A range does not store all of its numbers in memory. It calculates each number only when needed, so even range(1000000) is very small and fast to create. In Python 3 it is its own type, called range, not a list.
In this chapter you will learn the three forms of range(), the rule that the stop value is excluded, how to count backwards, and some useful patterns for real programs.
The three forms
| Form | Meaning | Example result |
|---|---|---|
| range(stop) | 0 up to stop-1 | range(4) -> 0, 1, 2, 3 |
| range(start, stop) | start up to stop-1 | range(2, 5) -> 2, 3, 4 |
| range(start, stop, step) | jump by step | range(0, 10, 3) -> 0, 3, 6, 9 |
The most important rule is that the stop value is never included. This matches how list slices work. A helpful trick: range(a, b) has exactly b - a numbers in it.
for i in range(5):
print(i, end=' ')
print()
for i in range(2, 6):
print(i, end=' ')Using a step
The third argument is the step. A step of 2 gives every second number, which is how you get even numbers or odd numbers. The step cannot be zero; Python raises a ValueError for that.
for n in range(2, 11, 2):
print(n, end=' ')Counting backwards
For a countdown use a negative step. The start must then be larger than the stop, otherwise the range is empty. Remember that the stop value is still excluded, so to include 1 you stop at 0.
for n in range(5, 0, -1):
print(n, end=' ')
print('Go!')Converting and inspecting a range
You can pass a range to list() to see its values. You can also use len(), the in operator, indexing and slicing on a range. These work without creating the full list in memory.
r = range(3, 20, 4)
print(list(r))
print(len(r), r[0], r[-1])
print(7 in r, 8 in r)Looping a fixed number of times
If you only need to repeat something and do not care about the number itself, name the variable _. This is a convention that tells readers the value is not used.
for _ in range(3):
print('Python')Looping over positions
Sometimes you need the position of each item, for example to change the list in place or to compare neighbours. Combine range() with len(). Be careful that the last valid index is len(items) - 1, which range(len(items)) handles correctly.
nums = [3, 8, 2, 9]
for i in range(1, len(nums)):
print(nums[i - 1], 'then', nums[i])Choosing good values
When you write a range, say in words what you want first. For example: I want the numbers from 10 down to 1. The first number is 10, the last number is 1, so the stop must be 0, and the step must be -1. Saying it aloud like this turns an abstract rule into a short checklist. Another check is to test with a very small case, such as range(1, 3), and list the result by hand. If your expectation matches the real output, you can trust the same pattern for larger values.
Ranges also work nicely with variables. If n holds the number of rows in a pattern, then range(n) repeats the work n times, and range(1, n + 1) lets you count from 1 to n. Because the values come from variables, the same program can handle small and large inputs without any change to the loop itself.
Typical patterns
- Sum of 1 to n: sum(range(1, n + 1)).
- Multiplication table: for i in range(1, 11): print(n, 'x', i, '=', n * i).
- Every third item of a list: items[::3] or for i in range(0, len(items), 3).
- Build a list of squares: [i * i for i in range(5)].
Arguments to range() must be integers. Writing range(2.5) or range(0, 1, 0.1) gives a TypeError. For decimal steps, calculate a value inside the loop, for example i / 10. Negative numbers are fine, so range(-3, 3) gives -3 up to 2.
Because the stop is excluded, a common off-by-one mistake is to forget to add 1 when you want the last number included. To print 1 to 10 you need range(1, 11), not range(1, 10).
Python syntax
range(stop)range(start, stop)range(start, stop, step)for i in range(len(items)):
bodyReal-world applications
- Repeating an action a fixed number of times.
- Printing numbered lists and tables.
- Accessing list items by position.
- Generating test data such as 1 to 100.
- Counting down timers or lives in games.
Common mistakes
Fix: Remember range(1, 5) ends at 4. Use range(1, 6) to include 5.
Fix: Use a negative step for counting down.
Fix: Use whole numbers and compute decimals inside the loop.
Fix: The step must be a non-zero integer.
Fix: Wrap it in list() to see the values.
Important tips
- Check the length with len(range(a, b)).
- Use _ when the number is not needed.
- Prefer enumerate() when you need both index and item.
- Test small ranges by converting to a list.
Key points summary
- range() gives integers lazily.
- The stop is excluded.
- The default start is 0 and the default step is 1.
- A negative step counts down.
- range supports len, in, indexing and slicing.
Exam and interview points
- range(5) is 0 to 4.
- range(1, 10, 3) gives 1, 4, 7.
- range(10, 0, -2) gives 10, 8, 6, 4, 2.
- range objects are immutable sequences.
- len(range(a, b)) equals max(0, b - a) for step 1.
Quick revision
- range(stop).
- range(start, stop).
- range(start, stop, step).
- Stop excluded.
- Negative step counts down.
Frequently asked questions
Is range() a list?
No. In Python 3 it is a special sequence type that saves memory. Use list(range(...)) if you need a real list.
Why is the stop not included?
It makes lengths easy: range(a, b) has b - a items, and ranges can be joined without overlapping.
Can I use range with floats?
No. Only integers are allowed. Use a loop with division or a library such as NumPy for decimal steps.
What does an empty range look like?
range(5, 2) has no numbers, so a loop over it runs zero times.
Practise this chapter
18 practice questions Take the chapter quiz