PYTHON
Combining Multiple Lists Element-wise with zip()
Learn how to elegantly combine elements from multiple lists into a single iterable of tuples using Python's `zip()` function, ideal for parallel data processing.
names = ["Alice", "Bob", "Charlie"]
ages = [30, 24, 35]
cities = ["New York", "London", "Paris"]
# Combine lists element-wise using zip()
combined_data = list(zip(names, ages, cities))
# Output:
# [('Alice', 30, 'New York'), ('Bob', 24, 'London'), ('Charlie', 35, 'Paris')]
print(combined_data)
# Iterate over zipped data
for name, age, city in zip(names, ages, cities):
print(f"{name} is {age} years old and lives in {city}.")
# Output:
# Alice is 30 years old and lives in New York.
# Bob is 24 years old and lives in London.
# Charlie is 35 years old and lives in Paris.
# 'Unzipping' data (reverse of zip)
new_names, new_ages, new_cities = zip(*combined_data)
print(f"Unzipped Names: {new_names}") # Output: Unzipped Names: ('Alice', 'Bob', 'Charlie')
print(f"Unzipped Ages: {new_ages}") # Output: Unzipped Ages: (30, 24, 35)
How it works: The `zip()` function is incredibly useful for combining elements from multiple iterables (like lists) into a single iterable of tuples. Each tuple contains elements from the corresponding positions in the input iterables. This is perfect for processing related data in parallel or creating structured data from separate lists. The snippet also shows how `zip(*iterable)` can be used to 'unzip' previously zipped data, effectively separating it back into its original components.