Python Loops: enumerate, zip, and itertools Recipes
Most Python loops are written one step below the abstraction that would express them clearly. A counter maintained by hand where enumerate already provides one, a nested index into two lists where zip pairs them, a recursion into index arithmetic where itertools.product names the idea â each substitution removes a variable and a class of off-by-one bugs. The deeper shift is recognising that many loops are not iteration problems at all: they are windowing, grouping, pairing, or combination problems, and the standard library already contains the implementation. This lesson works through the built-ins first, the itertools toolbox second, and the performance consequences last.
What You'll Learn
- 1Iterate with indices safely using enumerate and its start parameter
- 2Pair iterables with zip, including strict mode and unequal lengths
- 3Apply chain, product, combinations, groupby, and islice to real loops
- 4Recognise hot loops and apply the micro-optimisations that actually measure faster
Indexes without range(len)
range(len(items)) forces you to index manually, and every subscript is another chance to write the wrong variable. enumerate yields (index, element) pairs directly, works on any iterable including generators and file handles, and offers a start argument for human-facing numbering. It also makes the loop body independent of the container's type: the same code works for a list, a tuple, or a stream.
The pattern generalises in two directions worth knowing. When you need the previous element as well as the current one, pairwise-style code built from zip of shifted slices is clearer than index arithmetic. When you need indices for grouping or histogram work, feeding enumerate output straight into a defaultdict keeps the loop to a single assignment per iteration. Reserve range for loops where the index is genuinely the subject â numeric sequences, grid coordinates, and retries â rather than a substitute for the element you actually wanted.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
# 1. apple
# 2. banana
# 3. cherry
# previous element without index arithmetic
pairs = list(zip(fruits, fruits[1:]))
print(pairs) # [('apple', 'banana'), ('banana', 'cherry')]
width, height = 4, 3
grid = [(r, c) for r in range(height) for c in range(width)]
print(len(grid), grid[5]) # 12 (1, 1)
Pairing sequences with zip
zip takes one element from each iterable and stops at the shortest input, which is convenient until the lengths were supposed to be equal â then it silently truncates data. Python 3.10 added strict=True to raise ValueError on mismatched lengths, and that single argument has saved countless debugging sessions: if two columns must align, say so at the call site. When unequal lengths are expected, itertools.zip_longest pads with a fillvalue so no element is dropped.
Zip also generalises. zip(*matrix) transposes a table, zip(*pairs) splits keys from values into two lists, and repeated application walks nested structures you would otherwise index three levels deep. The cost is that zip returns an iterator, so materialise with list when you need to iterate twice. Keep in mind that zip stops at the shortest input, so an empty iterable anywhere in the call yields nothing at all â a common source of loops that never execute.
from itertools import zip_longest
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["New York", "London"]
for name, age in zip(names, ages):
print(f"{name} is {age}")
try:
list(zip(names, ages, cities, strict=True))
except ValueError as exc:
print("length mismatch:", exc) # strict catches the missing city
for name, city in zip_longest(names, cities, fillvalue="?"):
print(name, city)
keys = ["a", "b", "c"]
values = [1, 2, 3]
print(dict(zip(keys, values))) # {'a': 1, 'b': 2, 'c': 3}
a, b = zip(*[("x", 1), ("y", 2)]) # transpose into two tuples
print(a, b) # ('x', 'y') (1, 2)
Enable strict whenever the operands must align, and rely on the shortest-input rule only when truncation is genuinely the behaviour you want.
The itertools toolbox
itertools contains functions that each express one looping idea in C. chain flattens a sequence of iterables without building an intermediate list. product produces the Cartesian product, replacing nested loops over two ranges. combinations and permutations generate selections in lexicographic order, which is exactly what validation, testing, and scheduling code needs. islice slices an iterator without materialising it, so you can take the first thousand lines of a file that does not fit in memory.
Choosing among them is a translation exercise. If you would write two nested for loops over the same range, it is probably product. If you would write three nested loops to pick distinct triples, it is combinations. If the loops would re-derive indices and skip duplicates by hand, the itertools version removes both the arithmetic and the bug class.
import itertools
colors = ["red", "blue"]
sizes = ["S", "M"]
print(list(itertools.product(colors, sizes)))
# [('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]
items = ["A", "B", "C", "D"]
print(list(itertools.combinations(items, 2)))
# [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
print(list(itertools.chain([1, 2], [3], [], [4, 5]))) # [1, 2, 3, 4, 5]
print(list(itertools.islice(itertools.count(10), 4))) # [10, 11, 12, 13]
rolling = list(itertools.accumulate([1, 2, 3, 4]))
print(rolling) # [1, 3, 6, 10]
print(list(itertools.pairwise(rolling))) # [(1, 3), (3, 6), (6, 10)]
accumulate deserves a place in your default toolbox: running totals, prefix products, and cumulative maxima all fall out of it, and it accepts a custom function for anything associative. pairwise gives adjacent couples for change detection and smoothing without a single index.
Grouping, cycling, and stopping conditions
itertools.groupby collects consecutive runs of equal keys, which means the input must be sorted by that key first â the classic mistake is grouping unsorted data and getting one group per element. The idiom is sort with a key, then group, then consume each group iterator immediately, because the group objects are views into the underlying data and are invalidated when iteration moves on.
The loop-control keywords carry their own subtleties. break exits the innermost loop, continue skips to the next iteration, and the rarely used else clause on a loop runs only when no break occurred â a construct that reads oddly until you see its intended use: search until found, then handle the not-found case in else. while loops deserve the same discipline, with the loop condition written so the loop provably terminates.
from itertools import groupby
rows = [
("alice", "math"), ("alice", "science"),
("bob", "math"), ("carol", "science"),
]
rows.sort(key=lambda r: r[0])
for student, group in groupby(rows, key=lambda r: r[0]):
print(student, [subject for _, subject in group])
# alice ['math', 'science']
# bob ['math']
# carol ['science']
def find_first(predicate, items):
for item in items:
if predicate(item):
return item
return None
found = find_first(lambda n: n % 7 == 0, range(1, 100))
print(found) # 7
for n in range(2, 20):
if n % 2 == 0:
break
else:
print("no odd number found")
print(n) # 2 â loop exited via break
Where loops get slow, and what to change
Python loop overhead is real, but it is rarely where the time goes. Binding a frequently used global or method to a local name inside the loop removes repeated attribute lookups; membership tests against a set beat a list; and appending to a preallocated list beats repeated insert(0, ...) by orders of magnitude. Comprehensions outperform append loops mainly because they skip repeated method resolution, not because they are magic.
The table below ranks the changes by how often they matter. Anything in the first two rows is worth applying reflexively in hot code; the rest should be justified by a measurement, because readability bought in exchange for an unmeasurable gain is a net loss.
| Pattern in a hot loop | Cost | Better form |
|---|---|---|
| Global or attribute lookup each pass | Repeated dictionary lookups | Bind append = list.append or a method to a local |
value in some_list inside the loop | Linear scan per pass | Convert the list to a set before the loop |
items.insert(0, value) | Shifts every element | Append and reverse once, or use a deque |
| Manual index into two sequences | Interpreter overhead per subscript | zip the sequences |
| Building a list only to iterate it once | Extra allocation | Use a generator expression |
String concatenation with + | New object per pass | "".join(parts) collected in a list |
import time
from collections import deque
data = list(range(200_000))
pool = set(data)
start = time.perf_counter()
hits = 0
for i in range(50):
if i in data:
hits += 1
print("list scan", round(time.perf_counter() - start, 4))
start = time.perf_counter()
hits = 0
for i in range(50):
if i in pool:
hits += 1
print("set probe", round(time.perf_counter() - start, 6))
head = deque()
start = time.perf_counter()
for v in data:
head.appendleft(v)
print("deque ", round(time.perf_counter() - start, 4))
A caution about premature rewriting: profiles routinely show that a loop dominated by function calls, I/O, or string formatting gains almost nothing from these micro-changes. Measure with time.perf_counter around the section, apply one change, and measure again â if the number does not move, keep the clearer code.
Recipes that recur in real scripts
Four patterns account for a large share of everyday loop code: chunking a sequence into batches, scanning a sliding window over adjacent elements, filtering while accumulating, and early exit on a condition. Writing them as small generator functions makes each one composable â you can chain a chunker into a worker into a summariser, and the whole pipeline stays lazy, so memory use follows the batch size rather than the input size.
def chunked(items, size):
batch = []
for item in items:
batch.append(item)
if len(batch) == size:
yield batch
batch = []
if batch:
yield batch
def running_totals(values):
total = 0
for value in values:
total += value
yield total
def take_while(predicate, items):
for item in items:
if not predicate(item):
return
yield item
print(list(chunked(range(7), 3))) # [[0, 1, 2], [3, 4, 5], [6]]
print(list(running_totals([2, 1, 3]))) # [2, 3, 6]
print(list(take_while(lambda n: n < 5, range(10)))) # [1, 2, 3, 4]
Each generator yields lazily, which means the caller controls memory: chunked over a file handle loads one batch at a time, and take_while stops reading the source the moment the predicate fails rather than filtering the whole input first. That difference is what lets these recipes handle inputs larger than memory.
Common Mistakes
Looping with range(len(items)) and indexing inside the body
Fix: Use enumerate when you need the index, and iterate directly when you do not
Zip-ing sequences that must be the same length without checking
Fix: Pass strict=True on Python 3.10 and later so a mismatch raises instead of truncating
Calling groupby on unsorted data
Fix: Sort by the grouping key first; groupby only collects consecutive equal keys
Consuming a groupby group after moving to the next group
Fix: Materialise each group inside the loop â the group iterators are invalidated on advance
Micro-optimising a loop without measuring it
Fix: Time the section with perf_counter before and after, and keep the readable version if the number does not move
Best Practices
- Prefer enumerate, zip, and itertools over hand-written index arithmetic
- Turn repeated loop bodies into small generators so memory stays proportional to one batch
- Use strict=True when paired sequences are required to align
- Bind hot lookups to local names and membership tests to sets
- Write loop else clauses only for search patterns, where no break means not found
Interview Questions
Q1: What does zip do when the inputs have different lengths?
By default it stops at the shortest input, silently dropping the tail of longer ones. With strict=True it raises ValueError instead. itertools.zip_longest pads the shorter inputs with a fill value when you want every element kept.
Q2: Why does groupby sometimes return one group per element?
Because groupby only groups consecutive equal keys. If the data is not sorted by the key, runs are broken up and each occurrence becomes its own group. Sort first, then group.
Q3: When does a for loop's else clause run?
Only when the loop finishes without hitting break. It expresses search-then-handle logic: the else block runs when no match was found, and is skipped the moment a break exits the loop.
Key Takeaways
- enumerate and zip remove the index arithmetic where off-by-one bugs live
- zip truncates silently unless strict=True is set; zip_longest pads instead
- itertools turns nested loops into named combinators such as product and combinations
- groupby needs sorted input and immediate consumption of each group
- Optimise loops only after measuring: sets, locals, and joins are the changes that show up