A report prints numbered rows from one through five.
What You Need to Understand
range(stop) creates an efficient sequence of integers from zero up to but excluding stop. range(start, stop, step) controls the beginning and spacing. The range object does not allocate a list containing every integer.
When to Use It
A report prints numbered rows from one through five.
Step-by-Step Python Example
for number in range(1, 6):
print(number)
print(list(range(0, 10, 3)))
How the Example Works
The first loop prints 1 to 5, and the list is [0, 3, 6, 9]. Stop is exclusive.
Example Output
1
2
3
4
5
[0, 3, 6, 9]
[5, 4, 3, 2, 1]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
print(list(range(5, 0, -1)))
Important Behavior and Edge Cases
A step of zero raises ValueError. Negative steps are useful for descending counts, but start and stop must make sense for that direction.
Try It Yourself
Count down from five to one using range().
Common Beginner Mistakes
- A step of zero raises
ValueError. Negative steps are useful for descending counts, but start and stop must make sense for that direction. - Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
range(stop)creates an efficient sequence of integers from zero up to but excludingstop.- The first loop prints 1 to 5, and the list is
[0, 3, 6, 9]. - A step of zero raises
ValueError.