Sub topic 2
Python for Loops and the `range()` Function
Assume you know basic Python syntax, lists, strings, integers, and how to run a Python 3 script. This chapter focuses on choosing the clearest way to loop.
`range` is a lazy sequence, not a list
range() returns a range object. It stores the start, stop, and step values instead of storing every integer in a list. Python calculates values when needed.
The stop value is excluded. A range supports length, indexing, slicing, and membership tests.
r = range(2, 10, 2)
print(len(r)) # 4
print(r[1]) # 4
print(6 in r) # True
print(list(r)) # [2, 4, 6, 8]This makes range(1_000_000) much more memory-efficient than a list containing one million integers.
What happens to the loop variable
A for loop assigns each value to its loop variable. The variable remains bound after the loop and contains the last value. An empty loop never assigns it.
for number in range(3):
pass
print(number) # 2Python does not create a separate block scope for a loop.
Looping by index with `range(len(...))`
Use range(len(items)) when you specifically need integer indexes.
items = ["a", "b", "c"]
for index in range(len(items)):
print(index, items[index])When you need both the index and value, enumerate() is clearer.
Getting index and value with `enumerate()`
enumerate() produces pairs containing an index and an item. Its start argument changes the initial index.
names = ["Ada", "Grace", "Linus"]
for position, name in enumerate(names, start=1):
print(position, name)Looping over several iterables with `zip()`
zip() pairs items from multiple iterables. It stops when the shortest iterable ends.
names = ["Ada", "Grace"]
scores = [95, 88]
for name, score in zip(names, scores):
print(name, score)Controlling a loop with `break` and `continue`
break exits the loop immediately. continue skips the rest of the current iteration and starts the next one.
for number in range(1, 10):
if number == 6:
break
if number % 2 == 0:
continue
print(number) # 1, 3, 5Exercise
What does list(range(5, 0, -2)) produce?
Show answer
[5, 3, 1]. The stop value 0 is excluded.