pythons = ["Graham", "John", "Terry G", "Eric", "Terry J", "Michael"]
for name in pythons:
print(f"It's {name}")
A for loop in Python doesn't count. There's no index, no i < len(...), no off-by-one error waiting for you. It asks the thing on the right for its items one at a time and runs the block once for each. Lists, strings, dicts, open files and database cursors all work the same way.
That one idea covers most of the loops you'll ever write. The rest of this post is the parts that surprise people.
The loop variable outlives the loop
for name in pythons:
print(f"It's {name}")
print(f"Still {name}") # Still Michael
name isn't scoped to the loop. A for loop doesn't create a scope at all, so when it ends, name is still sitting there holding the last item. If you come from C or Java, or from JavaScript's let, this looks like a bug. It's the documented behavior.
It bites in two ways:
- You reuse a common name like
iorrowfurther down and read a stale value from a loop that finished forty lines ago. - The list was empty. The body never ran,
namewas never assigned, and using it after the loop raisesNameError. It passes every test and then fails for the one customer with no orders.
Comprehensions are the exception. The variable in [n.upper() for n in pythons] stays inside the brackets.
When you want the index: enumerate
for position, name in enumerate(pythons, start=1):
print(f"{position}. {name}")
If you catch yourself typing for i in range(len(pythons)):, stop and use enumerate. You get the position and the item together, and start=1 gives you human numbering without a + 1 scattered through the body.
Two lists at once: zip
born = [1941, 1939, 1940, 1943, 1942, 1943]
for name, year in zip(pythons, born, strict=True):
print(f"{name} was born in {year}")
zip pairs the items up. Left alone, it stops at the end of the shorter list and says nothing, which is a quiet way to lose data when one list came up short. strict=True (Python 3.10 and later) raises a ValueError instead. I pass it any time the lengths are supposed to match.
Looping over a dict
roles = {"Graham": "King Arthur", "John": "Sir Lancelot", "Eric": "Sir Robin"}
for name, role in roles.items():
print(f"{name} played {role}")
Looping over the dict itself gives you its keys. .items() gives you the pairs, and .values() gives you the values alone.
Don't change a list while you loop over it
numbers = [1, 2, 2, 3]
for n in numbers:
if n == 2:
numbers.remove(n)
print(numbers) # [1, 2, 3]
One of the 2s survived. Removing an item slides everything after it one place to the left, the loop moves on to the next position anyway, and an element gets stepped over. There is no error. Build a new list instead:
numbers = [n for n in numbers if n != 2]
A dict at least tells you. Add or remove a key mid-loop and you get RuntimeError: dictionary changed size during iteration.
for ... else
for name in pythons:
if name.startswith("Z"):
print(f"Found {name}")
break
else:
print("Nobody starts with Z")
The else block runs when the loop finishes without hitting break. Read it as "no break." It's useful for search loops, and unusual enough that I leave a comment whenever I use it.
Generators: looping over things that don't exist yet
def read_orders(path):
with open(path, encoding="utf-8") as handle:
for line in handle:
yield line.rstrip("\n").split(",")
for order in read_orders("orders.csv"):
print(order)
A function with yield in it is a generator. Calling it runs nothing. The for loop asks for a value, the function runs until its next yield, hands the value over, and pauses right there until it's asked again. One line of the file is in memory at a time, whether there are a hundred orders or a hundred million. That's the trick behind reading a file line by line.
You can get the same laziness without writing a function. Swap the square brackets of a comprehension for round ones:
squares_list = [n * n for n in range(10_000_000)] # builds ten million numbers right now
squares_gen = (n * n for n in range(10_000_000)) # builds nothing until you loop
The catch is that a generator only goes around once. The second loop over it gets nothing, and it doesn't complain:
evens = (n for n in range(10) if n % 2 == 0)
print(sum(evens)) # 20
print(sum(evens)) # 0
If you need the values twice, make a list. If you need them once and there are a lot of them, make a generator.
The short version
- A
forloop walks an iterable. It doesn't count. - The loop variable is still alive after the loop, and was never created if the loop didn't run.
enumeratefor positions,zip(..., strict=True)for parallel lists,.items()for dicts.- Never add to or remove from the list you're looping over.
- Generators give you one item at a time, exactly once.
Slices go well with all of this, for the times you only want part of a list. I wrote up slice notation separately.
-Sethers