Python range: exclusive stop, negative steps and indices
Use Python range with an exclusive stop, negative steps and empty results. Choose safe bounds for neighboring indices and understand inclusive endpoints.
Your loop stops one number early, or does nothing when you swap its bounds. Then you add items[i + 1] and the last iteration goes past the list. For each case, write down the condition every generated value must satisfy.
In short
range(start, stop, step) produces integers starting at start, adding step each time, without reaching or crossing stop. With a positive step, values stay strictly below stop; with a negative step, they stay strictly above it. To read neighboring elements items[i] and items[i + 1], use range(len(items) - 1): the last starting index is len(items) - 2.
What do start, stop and step mean?
start is the first candidate integer, stop is the excluded bound, and step is the difference between consecutive values. With one argument, the start defaults to zero and the step to one.
print(list(range(4)))print(list(range(2, 6)))print(list(range(2, 10, 3)))print(list(range(0)))$ python3 bounds.py[0, 1, 2, 3][2, 3, 4, 5][2, 5, 8][]For range(2, 10, 3), the candidates are 2, 5, 8, then 11. The condition is “value < 10”, which 11 fails. The sequence doesn't have to land exactly on the bound to stop.
The last generated number isn't necessarily stop - 1. It also depends on the start and step. Here it is 8. The calls to list make the sequences visible; a loop can iterate over a range directly without building that list.
Why is the stop value excluded?
This convention matches sequence indices: a list of length four has indices zero through three. It also lets you join adjacent ranges without repeating their shared boundary.
items = ["a", "b", "c", "d"]for i in range(len(items)): print(i, items[i])print(list(range(0, 2)) + list(range(2, 4)))$ python3 indices.py0 a1 b2 c3 d[0, 1, 2, 3]- 0avisited index
- 1bvisited index
- 2cvisited index
- 3dvisited index
- 4stopexcluded bound
The last cell represents the bound, not a fifth element of items. Index four would be outside the list.
If you only need the values, iterate over items directly. If you need each value with a counter, enumerate expresses that task more directly. Use range when you need to calculate positions, such as the index of a neighbor.
How do you count backward with a negative step?
Use a negative step and place the start above the stop. Swapping the bounds without changing the step produces an empty sequence.
print(list(range(4, 0, -1)))print(list(range(4, -1, -1)))print(list(range(4, 0)))print(list(range(0, 4, -1)))print(list(range(2, 2, -1)))$ python3 backward.py[4, 3, 2, 1][4, 3, 2, 1, 0][][][]The first call stops before zero. The second reaches zero because its excluded bound is minus one. The last three sequences are empty: their first candidate already fails the condition set by the step's direction. These empty ranges don't raise an exception.
A negative start doesn't mean “count backward”. range(-3, 1) moves toward larger values with the default step. The sign of step sets the direction.
How do you include an endpoint?
For an inclusive integer interval, move the excluded bound one unit in the direction of travel: end + 1 going up, end - 1 going down. This doesn't add values that the step cannot reach.
print(list(range(1, 5 + 1)))print(list(range(5, 1 - 1, -1)))print(list(range(2, 9 + 1, 3)))print(list(range(2, 8 + 1, 3)))$ python3 inclusive.py[1, 2, 3, 4, 5][5, 4, 3, 2, 1][2, 5, 8][2, 5, 8]The third call allows values up to nine inclusive, but nine isn't in the progression 2, 5, 8, 11. The last call reaches eight. An allowed endpoint and a generated value are different things.
Which bound is safe when you use i + 1?
To read an element and its right neighbor, stop the starting indices before the final element. A sequence of length n has n - 1 adjacent pairs when n is positive.
for text in ["4567", "x", ""]: pairs = [] for i in range(len(text) - 1): pairs.append((i, text[i:i + 2])) print(repr(text), pairs)$ python3 neighbors.py'4567' [(0, '45'), (1, '56'), (2, '67')]'x' []'' []With four characters, the starting indices are zero, one and two. On the last iteration, i + 1 is three, so both accesses remain valid. The slice displays the pair here; the same range would let you read text[i] and text[i + 1] separately.
For one character, range(0) is empty. For an empty string, range(-1) is empty too. The loop therefore accesses no characters in either case. You can reason about the bound without adding a special branch.
count_digit_steps
Count adjacent digit pairs where the second digit is exactly one greater than the first. The contract allows overlapping pairs, so starting indices must advance by one position, not two. A non-digit breaks adjacency, and 9 followed by 0 doesn't count.
The exercise adds a condition on each pair's contents. The traversal bound is the part covered here. To combine two sources instead of calculating indices, read zip and different lengths.
Is range a list or a generator?
range is an immutable sequence of integers. It stores a description of the progression without materializing every integer, and you can iterate over it more than once. An iterator created from that range advances as you read it.
r = range(3)print(list(r))print(list(r))it = iter(r)print(next(it))print(list(it))print(list(it))for args in [(0, 3, 0), (0, 3.0, 1)]: try: range(*args) except (ValueError, TypeError) as error: print(type(error).__name__)$ python3 reuse.py[0, 1, 2][0, 1, 2]0[1, 2][]ValueErrorTypeErrorA zero step is invalid and raises ValueError. Arguments must be integers or implement the integer index protocol; a float such as 3.0 won't work. Use integers for list positions.
Don't convert a large range to a list just to iterate over it. A list stores all its elements. The range stays compact; any additional storage depends on what your loop does.
Frequently asked questions
Does range(5) contain five?
No. It contains five integers, from zero through four. For integers one through five, use range(1, 6).
Why does range(5, 1) produce nothing?
The default step is one. The start, five, is already above the excluded bound, one, while that step requires values strictly below the bound. Use a negative step to count down.
Can you change the values in a range?
No, it is an immutable sequence. Create another range for different bounds, or convert it to a list if you need to change its elements.
Sources
