The for loop with range in Python provides a clean and efficient way to repeat blocks of code a specific number of times. This pattern combines the for keyword, the range function, and a block of statements to control iteration precisely.
Understanding how range works with for loops helps you write clearer, more predictable code when you need to repeat actions based on numeric sequences.
| Keyword | Description | Example Expression | Resulting Sequence |
|---|---|---|---|
| range | Generates a sequence of integers | range(4) | 0, 1, 2, 3 |
| range | Generates values from a start to stop minus one | range(2, 6) | 2, 3, 4, 5 |
| range with step | Increments by a custom step value | range(0, 10, 2) | 0, 2, 4, 6, 8 |
| Negative step | Counts downward when step is negative | range(5, 0, -1) | 5, 4, 3, 2, 1 |
Using range as the stop argument in for loops
Basic single argument form
Using range(stop) starts counting at 0 and ends at stop minus one. This is the simplest way to run a loop a known number of times.
Specifying start and stop in for loops with range
Two argument form for custom start values
Providing both start and stop as range(start, stop) allows you to begin at a number other than zero and still iterate forward to stop minus one.
Using step to control iteration spacing
Three argument form with step
The third argument range(start, stop, step) controls the increment between values, enabling loops that skip indices or count by larger intervals.
Handling edge cases and common mistakes
Empty ranges and off-by-one behavior
When start equals stop or the step direction does not move toward stop, the loop body never executes, which can surprise developers expecting one iteration.
Best practices for for loops with range in Python
- Prefer direct iteration over iterables when you do not need numeric indices
- Use enumerate when you need both index and element from a sequence
- Choose step values carefully to avoid off-by-one errors
- Validate that start, stop, and step move in a consistent direction
- Keep loop bodies focused to preserve readability and ease debugging
FAQ
Reader questions
Can range generate a decreasing sequence in a for loop?
Yes, you can create a decreasing sequence by setting a negative step and ensuring start is greater than stop, for example range(10, 0, -2) yields 10, 8, 6, 4, 2.
Does modifying the loop variable inside a for range loop affect iteration?
Reassigning the loop variable inside the body does not change the iteration sequence produced by range, which is precomputed before the loop starts.
Can range with for loops work with negative start and stop values?
Yes, range works with negative numbers, and the loop runs as long as the progression moves toward the stop value given the sign of the step.