By the end of this lesson, you will be able to generate integer sequences using Python's range() function to control loop iterations efficiently.
What it is
The range() function in Python returns an immutable sequence of numbers. It is commonly used for looping a specific number of times in for loops. Unlike creating a list of numbers, range() generates values on demand (lazy evaluation), making it memory-efficient even for very large sequences. The key parameters are start, stop, and step.
Why it matters
- Memory Efficiency: It does not store all numbers in memory at once, allowing you to iterate over millions of integers without crashing your program.
- Readability: It provides a clear, standard way to express iteration counts compared to manual counter variables.
- Flexibility: Supports custom start points, stop points, and step increments (including negative steps).
- Integration: Works seamlessly with other iterable functions like
enumerate()and list comprehensions.
Syntax or steps
The general syntax is range(start, stop, step). If arguments are omitted, defaults apply: start defaults to 0, and step defaults to 1. Note that the stop value is always exclusive.
- Define the starting integer (optional, default 0).
- Define the stopping integer (required, exclusive).
- Define the step size (optional, default 1).
- Use the result directly in a
forloop header.
Example
# Basic usage: counting from 1 to 5
for i in range(1, 6):
print(i)
# Using step: counting by 2s
for j in range(0, 10, 2):
print(j)
# Reverse order: counting down
for k in range(5, 0, -1):
print(k)
In the first block, range(1, 6) produces 1, 2, 3, 4, 5. The number 6 is excluded. In the second block, range(0, 10, 2) starts at 0 and adds 2 each time until reaching but not including 10. In the third block, a negative step reverses the direction.
Common mistakes
- Off-by-one errors: Forgetting that the
stopargument is exclusive. To include 10, userange(11)orrange(0, 11). - Confusing with lists: Trying to modify the output of
range()as if it were a mutable list. You must convert it usinglist(range(...))if you need list operations. - Incorrect step sign: Using a positive step when the start is greater than the stop results in an empty sequence. Ensure the step direction matches the desired flow.
- Non-integer arguments:
range()only accepts integers. Passing floats will raise aTypeError.
When to use it
Compare range() with iterating over a pre-created list.
| Feature | range() | List Iteration |
|---|---|---|
| Memory Usage | Low (constant) | High (proportional to length) |
| Speed | Faster for simple counters | Slower due to allocation |
| Use Case | Fixed numeric sequences | Existing data collections |
Use range() when you need to repeat an action N times or iterate through indices. Use list iteration when you already have the data structure.
Practice
Guided Exercise: Write a loop that prints all even numbers from 2 to 20 inclusive.
Hint: Use range(2, 21, 2).
Challenge: Create a countdown timer simulation that prints "T-minus X" from 10 down to 1, then prints "Liftoff!".
Expected Output: T-minus 10 ... T-minus 1 Liftoff!
Quick check
Question: What does list(range(5)) return?
Answer: [0, 1, 2, 3, 4]
Summary
The range() function is essential for efficient numeric iteration in Python. Remember that the stop value is exclusive and that it generates values lazily to save memory. Mastering its three parameters allows for precise control over loop behavior.