Nearby lessons
48 of 159Python - zip() Function
📌 What You Will Learn
- Explain how zip() combines iterables
- Unpack zipped values in a for loop
- Use zip() to create dictionaries
- Handle iterables with unequal lengths
- Convert a zip object into a list
Combining related sequences
zip() is useful when values at the same position belong together, such as names and scores.
Basic syntax
Use zip(iterable1, iterable2, ...). Each result item is a tuple containing one value from each input.
Loop over two lists together
Inspecting the zip object
Building a dictionary
Unequal lengths
Regular zip() stops at the shortest iterable, so extra values in longer inputs are ignored.
Unzipping pairs
Use the unpacking operator with zip() to separate pairs back into columns.
When to use zip_longest()
Import zip_longest() from itertools when every item from unequal-length inputs should be processed with a fill value.
📝 Key Takeaways
- zip() groups corresponding elements into tuples
- The result is a lazy zip iterator
- Iteration stops when the shortest iterable is exhausted
- dict(zip(keys, values)) is a convenient dictionary pattern
- Use itertools.zip_longest() when missing values should be retained
🧠 Test Your Knowledge
8 QuestionsProgress: 0 / 8