zip() pairs up the corresponding elements of each iterable into a tuple, producing a lazy iterator that stops as soon as the shortest input is exhausted, silently truncating longer iterables unless you pass strict=True (Python 3.10+), which instead raises ValueError on a length mismatch. Passing a single unpacked list of lists to zip() is the standard idiom for transposing rows and columns.
1Understanding zip()
zip() pairs up the corresponding elements of each iterable into a tuple, producing a lazy iterator that stops as soon as the shortest input is exhausted, silently truncating longer iterables unless you pass strict=True (Python 3.10+), which instead raises ValueError on a length mismatch. Passing a single unpacked list of lists to zip() is the standard idiom for transposing rows and columns.
Use zip() with the unpacking operator on a matrix (a list of lists) to transpose rows and columns — it's a common, slightly non-obvious trick worth memorizing.
names = ["Alice", "Bob"]
ages = [30, 25]
for name, age in zip(names, ages):
print(f"{name} is {age}")2Practical Example
Here is a real-world application of zip() showing how it is used in production Python code.
matrix = [[1, 2, 3], [4, 5, 6]]
transposed = list(zip(*matrix))
print(transposed)3Best Practices
Follow these guidelines when working with zip():
1. Pass strict=True (Python 3.10+) when iterables should be the same length, so a mismatch fails loudly instead of silently truncating data
2. Use zip() to iterate over two related sequences in parallel instead of indexing with range and len
3. Wrap zip() in dict() to build a dictionary directly from two parallel sequences of keys and values
Tip: Use zip() with the unpacking operator on a matrix (a list of lists) to transpose rows and columns — it's a common, slightly non-obvious trick worth memorizing.
names = ["Alice", "Bob"]
ages = [30, 25]
for name, age in zip(names, ages):
print(f"{name} is {age}")