Python zip() Tutorial#
The zip() function in Python combines multiple iterables (lists, tuples, dictionaries, etc.) element-wise into tuples.
It is commonly used for:
✅ Pairing elements from multiple lists ✅ Iterating over multiple lists simultaneously ✅ Unzipping (extracting back original lists) ✅ Transforming a Transport Matrix
Summary of zip() Usage#
| Use Case | Code Example |
|---|---|
| Pair elements | zip(list1, list2) |
| Loop over pairs | for a, b in zip(list1, list2): |
| Unzip data | zip(*zipped_data) |
| Handle different lengths | itertools.zip_longest(list1, list2, fillvalue='?') |
| Sort together | sorted(zip(scores, names)) |
| Create a dictionary | dict(zip(keys, values)) |
| Extract transport matrix columns | list(zip(*matrix)) |
1️⃣ Basic Usage of zip()#
🟢 Combining Two Lists
| |
✅ Pairs elements from both lists into tuples.
2️⃣ Iterating Over zip()#
| |
Output:
| |
✅ Iterates through paired elements from two lists.
3️⃣ Using zip(*iterable) to Unzip Data#
| |
✅ Extracts back original lists using zip(*).
4️⃣ zip() with Different Length Lists#
| |
✅ Stops at the shortest iterable to avoid IndexError.
🔹 If you need to fill missing values, use itertools.zip_longest()
| |
5️⃣ Sorting with zip()#
| |
✅ Sorts names based on scores using zip().
6️⃣ Creating a Dictionary Using zip()#
| |
✅ Efficiently converts two lists into a dictionary.
7️⃣ Using zip() in Transport Matrix#
The zip() function can be used to transpose a transport matrix, making it easier to access columns instead of rows.
Example: Transport Matrix#
| |
Output:#
| |
✅ zip(*cost_matrix) converts rows into columns, making store-wise access easier.