How to Use Range Function in Python: Syntax and Examples
The
range() function in Python generates a sequence of numbers, commonly used in loops. You can call it with one, two, or three arguments: range(stop), range(start, stop), or range(start, stop, step) to control the sequence start, end, and step size.Syntax
The range() function can be used in three ways:
range(stop): Generates numbers from 0 up to but not includingstop.range(start, stop): Generates numbers fromstartup to but not includingstop.range(start, stop, step): Generates numbers fromstartup to but not includingstop, incrementing bystep.
All arguments must be integers. The step can be negative to count backwards.
python
range(stop) range(start, stop) range(start, stop, step)
Example
This example shows how to use range() in a for loop to print numbers from 0 to 4, then from 2 to 5, and finally counting backwards from 5 to 1.
python
for i in range(5): print(i, end=' ') print() for i in range(2, 6): print(i, end=' ') print() for i in range(5, 0, -1): print(i, end=' ') print()
Output
0 1 2 3 4
2 3 4 5
5 4 3 2 1
Common Pitfalls
Common mistakes include:
- Using a non-integer argument causes an error.
- Forgetting that
stopis exclusive, so the last number is not included. - Using a
stepof zero, which raises an error. - Confusing the order of
startandstopwhen counting backwards.
python
try: list(range(1.5, 5)) # Wrong: float arguments except TypeError as e: print(f"Error: {e}") # Correct usage print(list(range(1, 5)))
Output
Error: 'float' object cannot be interpreted as an integer
[1, 2, 3, 4]
Quick Reference
| Usage | Description | Example |
|---|---|---|
| range(stop) | Numbers from 0 up to stop (exclusive) | range(5) → 0,1,2,3,4 |
| range(start, stop) | Numbers from start up to stop (exclusive) | range(2, 6) → 2,3,4,5 |
| range(start, stop, step) | Numbers from start to stop by step | range(5, 0, -1) → 5,4,3,2,1 |
Key Takeaways
Use range() to generate sequences of integers for loops and iterations.
The stop value is exclusive; the sequence stops before it reaches stop.
You can specify start, stop, and step to control the sequence.
Step cannot be zero and must be an integer.
range() arguments must be integers; floats cause errors.