Understand the idea
A condition selects a branch. A loop repeats work while advancing through a finite set or toward a stopping condition. Indentation defines Python blocks; range(a,b) includes a and excludes b.
Work through an example
The loop examines 1,7,2 after initializing best=4. Only the comparison with 7 enters the update branch. A while loop can do the same with i starting at 1 and increasing each visit.
Time and space complexity
One visit per element gives O(n) time. The slicing version allocates O(n) extra space; the indexed version uses O(1).
Why it works
After processing an index, best is the maximum of the processed prefix.
Common mistakes
- Forgetting i+=1 can make a while loop infinite.
- range(len(values)+1) reaches an invalid index.
Chapter lab · Python implementation
Our running task is to find the largest value in a sequence. A program turns a precise input/output contract into small state changes. Read the example from the top, predict each update, and run its assertions. Python examples use ordinary built-in types; statements inside an indented block belong to that block.
This shared lab connects the chapter's topics. Follow the current lesson's worked example first, then trace the complete implementation. Additional algorithms described in topic exercises are variations you can implement independently.
def largest(values):
if not values:
return None
best = values[0]
for value in values[1:]:
if value > best:
best = value
return best
def largest_without_slice(values):
if not values:
return None
best = values[0]
for i in range(1, len(values)):
best = max(best, values[i])
return bestRun and test the lab
Copy the implementation and these assertions into a Python 3 file and run it. An assertion failure means the actual result differs from the expectation. Add the current topic's exercise and boundary tests to deepen your understanding.
assert largest([]) is None
assert largest([-8, -3, -5]) == -3
assert largest_without_slice([4, 1, 7, 2]) == 7
assert largest_without_slice([0]) == 0Does a loop body execute on range(0)?
Further reading
Original documentation for the implementation details used in this chapter.
Python data structures