38. Python zip and unzip

Here are Python code snippets demonstrating how to use zip to combine iterables and how to use * for unpacking, including examples of both zipping and unzipping iterables:

1. Basic Usage of zip

This example shows how to zip two lists together.

Copy

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

zipped = zip(list1, list2)
zipped_list = list(zipped)
print(zipped_list)
# Output: [(1, 'a'), (2, 'b'), (3, 'c')]

2. Unzipping with zip and *

To unzip, you can use the * operator with zip to unpack the elements back into separate lists.

Copy

zipped_list = [(1, 'a'), (2, 'b'), (3, 'c')]
unzipped = zip(*zipped_list)

list1, list2 = list(unzipped)
print(list1)  # Output: [1, 2, 3]
print(list2)  # Output: ['a', 'b', 'c']

3. Zipping Multiple Iterables

You can zip more than two iterables together.

Copy


4. Zipping with Different Lengths

If the iterables have different lengths, zip will stop when the shortest iterable is exhausted.

Copy


5. Using zip with Dictionaries

You can use zip to create dictionaries by pairing keys and values.

Copy


6. Zipping and Unzipping with Iterables of Unequal Lengths

You can handle unequal lengths by using itertools.zip_longest for zipping.

Copy


7. Unzipping and Repacking

This shows how you can unzip a zipped iterable and then repack it.

Copy


8. Unpacking with * to Pass Arguments

You can use * to unpack a zipped object and pass it as arguments to a function.

Copy


9. Zipping with a Custom Function

You can also zip elements from multiple iterables using a custom function to combine them.

Copy


10. Zipping and Iterating with Indices

You can use zip with enumerate to iterate over elements with indices.

Copy


These code snippets provide a variety of use cases for zip and unpacking with *, showing how to combine iterables, handle different lengths, and use the zipped data in different contexts.

Last updated