Python Control Flow
Python range() Function
range() generates a sequence of numbers on demand, and is most often used to control how many times a for loop runs.
range(stop) — One Argument
When you pass a single number to range(), it produces numbers starting at 0 up to (but not including) that number. This makes range(5) produce 0, 1, 2, 3, 4 — five values in total.
for i in range(5):
print(i)range(start, stop) — Two Arguments
Passing two numbers sets a custom starting point. range(start, stop) counts from start up to, but not including, stop.
for i in range(2, 7):
print(i)range(start, stop, step) — Three Arguments
A third argument sets the step size, letting you count by twos, count backwards, or skip values. A negative step counts downward.
for i in range(10, 0, -2):
print(i)| Call | Values produced |
|---|---|
| range(5) | 0, 1, 2, 3, 4 |
| range(2, 6) | 2, 3, 4, 5 |
| range(0, 10, 2) | 0, 2, 4, 6, 8 |
| range(5, 0, -1) | 5, 4, 3, 2, 1 |
range() Inside for Loops
range() is most commonly used to repeat an action a fixed number of times, or to loop by index when you need position information alongside your data.
names = ["Asha", "Rahul", "Meera"]
for i in range(len(names)):
print(i, names[i])Converting range() to a List
range() itself does not create a list — it produces a memory-efficient range object that generates numbers as needed. Wrap it in list() when you actually need a real list, for example to print it directly or pass it to functions expecting a list.
numbers = list(range(1, 6))
print(numbers)[1, 2, 3, 4, 5]Prefer for item in names: over for i in range(len(names)): when you don’t actually need the index — it is simpler and more Pythonic. Reach for enumerate() when you need both.
