Python Code Example: Zipping Lists Together

Zipping lists together is a useful technique when you want to combine multiple lists into a single iterable where each element is a tuple containing elements from the input lists at the corresponding positions. The zip() function accomplishes this efficiently. This is particularly helpful for iterating over multiple lists in parallel or for creating dictionaries from two lists of keys and values.

Code Example

# Define two lists of equal length
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

# Use the zip() function to combine the lists into a list of tuples
zipped_list = list(zip(names, ages))

# Print the resulting list of tuples
print(f"Zipped list: {zipped_list}")

# Use zip() in a loop to iterate over the zipped lists
for name, age in zipped_list:
    print(f"{name} is {age} years old")

Code Explanation

Defining the Lists

Two lists, names and ages, are defined. These lists are of equal length, which is a common requirement when using the zip() function.

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

Using the zip() Function

The zip() function is used to combine names and ages into a single iterable of tuples. Each tuple contains elements from the input lists at the corresponding positions.

zipped_list = list(zip(names, ages))
  • Combining Lists: zip(names, ages) returns an iterator of tuples, where each tuple contains one element from each of the input lists.
  • Converting to List: list(zip(names, ages)) converts the iterator to a list of tuples for easier manipulation and display.

Printing the Zipped List

The resulting list of tuples is printed.

print(f"Zipped list: {zipped_list}")

Iterating Over the Zipped List

The zipped list is iterated over in a loop, and each element of the tuple is accessed directly within the loop. This demonstrates how to work with the zipped data.

for name, age in zipped_list:
    print(f"{name} is {age} years old")