Projects/zipping_lists.py
2025-09-12 20:37:36 -07:00

45 lines
1.8 KiB
Python

list_a = [1, 2, 3]
list_b = [4, 5, 6]
"""
This script demonstrates how to zip and unzip two lists in Python.
- `list_a` and `list_b` are two lists of integers.
- The `zip()` function combines these lists into a list of tuples, pairing elements by their positions.
- The zipped result is printed.
- The script then shows how to unzip the zipped list using unpacking (`*`) and `zip()`, resulting in tuples containing
the original lists' elements.
- The unzipped tuples are converted back to lists using `map(list, ...)`.
- The final output confirms that the original lists are successfully recovered after zipping and unzipping.
Example output:
list_a: [1, 2, 3]
list_b: [4, 5, 6]
list_a and list_b zipped: [(1, 4), (2, 5), (3, 6)]
zipped list unzipped: [(1, 2, 3), (4, 5, 6)]
list_a unzipped: [1, 2, 3]
list_b unzipped: [4, 5, 6]
"""
print('list_a:', list_a)
print('list_b:', list_b)
zipped = zip(list_a, list_b)
print('list_a and list_b zipped:', list(zipped)) # Output: [(1, 4), (2, 5), (3, 6)]
# Unzipping
unzipped = zip(*zip(list_a, list_b))
print('zipped list unzipped:', list(unzipped)) # Output: [(1, 2, 3), (4, 5, 6)]
# Note: The unzipped output is a list of tuples, each containing elements from the original lists.
# To convert tuples back to lists
list_a_unzipped, list_b_unzipped = map(list, zip(*zip(list_a, list_b)))
print('list_a unzipped:', list(list_a_unzipped)) # Output: [1, 2, 3]
print('list_b unzipped:', list(list_b_unzipped)) # Output: [4, 5, 6]
# Use cases
for num, char in zip([1, 2, 3], ['a', 'b', 'c']):
print('num', num, 'char', char)
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
nums, chars = zip(*pairs)
print('list of unzipped pairs:', list(zip(*pairs)))
print('list of nums:', list(nums)) # (1, 2, 3)
print('list of chars:', list(chars)) # ('a', 'b', 'c')