Practice question · Multiple choice
A loop written for i in range(1, 10) runs nine times, not ten. Why is the convention half-open rather than an off-by-one waiting to happen?
Hints
- Compute the length of
range(1, 10)and ofrange(10, 20)using only the two numbers. - Now write them next to each other and ask which values are covered twice, and which not at all.
Show the answer
C. Because the length is stop minus start, and ranges join cleanly
Why
Half-open intervals make length arithmetic trivial and make range(0,10) and range(10,20) tile the numbers exactly once. Both closed ends would force a everywhere and a decision about the boundary at every join. The convention costs one moment of surprise and removes a whole class of slicing bugs, which is why it is near-universal.
Practise Algorithms, variables, and control flow
The app has 8 more questions on this lesson, and keeps your place in the course. Physics I is free to start.