How to Use zip() Function in Python: Syntax and Examples
The
zip() function in Python combines multiple iterables (like lists or tuples) into pairs or tuples of corresponding elements. It stops when the shortest input iterable is exhausted, returning an iterator of tuples.Syntax
The zip() function syntax is simple:
zip(iterable1, iterable2, ...): Takes two or more iterables as arguments.- Returns an iterator of tuples, where each tuple contains one element from each iterable at the same position.
- The length of the result matches the shortest input iterable.
python
zip(iterable1, iterable2, ...)Example
This example shows how zip() pairs elements from two lists into tuples:
python
names = ['Alice', 'Bob', 'Charlie'] ages = [25, 30, 35] paired = list(zip(names, ages)) print(paired)
Output
[('Alice', 25), ('Bob', 30), ('Charlie', 35)]
Common Pitfalls
Common mistakes when using zip() include:
- Expecting
zip()to return a list directly (it returns an iterator, so you often need to convert it withlist()). - Not realizing
zip()stops at the shortest iterable, which can cause data loss if inputs differ in length.
python
list1 = [1, 2, 3, 4] list2 = ['a', 'b'] # Wrong: expecting all pairs print(list(zip(list1, list2))) # Output: [(1, 'a'), (2, 'b')] - stops at shortest # Right: handle different lengths explicitly from itertools import zip_longest print(list(zip_longest(list1, list2, fillvalue=None))) # Output: [(1, 'a'), (2, 'b'), (3, None), (4, None)]
Output
[(1, 'a'), (2, 'b')]
[(1, 'a'), (2, 'b'), (3, None), (4, None)]
Quick Reference
| Feature | Description |
|---|---|
| Input | Two or more iterables (lists, tuples, strings, etc.) |
| Output | Iterator of tuples pairing elements by position |
| Stops at | Shortest input iterable length |
| Convert to list | Use list(zip(...)) to see all pairs at once |
| Handle uneven lengths | Use itertools.zip_longest() with fillvalue |
Key Takeaways
Use zip() to combine elements from multiple iterables into tuples by position.
zip() returns an iterator, so convert it to a list to view all pairs immediately.
zip() stops at the shortest iterable, so data may be lost if lengths differ.
Use itertools.zip_longest() to handle iterables of different lengths safely.
zip() works with any iterable, including lists, tuples, and strings.