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:
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.
list1 = ['apple', 'banana', 'cherry']
list2 = ['red', 'yellow', 'dark red']
zipped = zip(list1, list2)
for idx, (fruit, color) in enumerate(zipped):
print(f"{idx}: {fruit} is {color}")
# Output:
# 0: apple is red
# 1: banana is yellow
# 2: cherry is dark red