When programming, you often encounter situations where related data is stored in separate lists, such as a “list of names” and a “list of ages,” and you want to retrieve and process them simultaneously. While you could access them using an index like list1[i], list2[i], Python provides a smarter and more readable way: the built-in zip() function.
This article explains how to use the zip() function to loop through multiple lists at the same time and what happens when the lists have different lengths.
1. Basic Usage (Two Lists)
When you pass multiple lists (or iterables) as arguments to the zip() function, it returns a sequence of tuples, where each tuple contains elements from the input lists at the same index. You can unpack these tuples in a for loop to process them simultaneously.
Syntax:
for var1, var2 in zip(list1, list2):
# Process
Example: Here is a program that processes and displays a list of product names and a list of their prices simultaneously.
# List of product names
product_names = ["Apple", "Orange", "Banana"]
# List of prices
product_prices = [150, 200, 120]
print("--- Price List ---")
# Combine two lists with zip()
for name, price in zip(product_names, product_prices):
print(f"Product: {name} | Price: {price} yen")
Output:
--- Price List ---
Product: Apple | Price: 150 yen
Product: Orange | Price: 200 yen
Product: Banana | Price: 120 yen
2. Processing Three or More Lists Simultaneously
The zip() function works similarly for three or more lists. Just add the lists to the arguments and increase the variables in the for loop.
Example: Here is an example of processing three lists: “Name”, “ID”, and “Department” of employees together.
names = ["Tanaka", "Sato", "Suzuki"]
ids = [101, 102, 103]
departments = ["Sales", "Engineering", "HR"]
print("--- Employee Data ---")
for name, emp_id, dept in zip(names, ids, departments):
print(f"ID: {emp_id}, Name: {name}, Dept: {dept}")
Output:
--- Employee Data ---
ID: 101, Name: Tanaka, Dept: Sales
ID: 102, Name: Sato, Dept: Engineering
ID: 103, Name: Suzuki, Dept: HR
3. Behavior When Lists Have Different Lengths (Important)
The most important thing to note when using the zip() function is how it behaves when the passed lists have different lengths (number of elements). zip() stops the loop as soon as the shortest list runs out of elements. This means the remaining elements of the longer lists are ignored (truncated).
# Lists with different lengths
list_short = ["A", "B"]
list_long = [1, 2, 3, 4, 5]
print("--- Loop Start ---")
for char, num in zip(list_short, list_long):
print(f"{char} - {num}")
print("--- Loop End ---")
Output:
--- Loop Start ---
A - 1
B - 2
--- Loop End ---
The loop stopped when list_short ran out of elements, and 3, 4, 5 in list_long were not processed. This behavior is convenient if intended, but it can also cause bugs where data loss goes unnoticed.
4. Raising an Error When Lengths Differ (strict=True)
If you are proceeding on the premise that “the list lengths must be the same” and want to detect a mismatch as an error, specify the strict=True option in the zip() function (available in Python 3.10 and later).
list_short = ["A", "B"]
list_long = [1, 2, 3]
# Specifying strict=True raises a ValueError if lengths do not match
# for char, num in zip(list_short, list_long, strict=True):
# print(f"{char} - {num}")
# Execution Result:
# ValueError: zip() argument 2 is longer than argument 1
This allows you to immediately discover unexpected data inconsistencies.
Summary
- Use the
zip()function to loop through multiple lists simultaneously. - Write it like
for a, b in zip(list_a, list_b):. - It can handle three or more lists at once.
- If the lists have different lengths,
zip()stops at the end of the shortest list, and the rest are ignored. - If you want to ensure data consistency, consider using the
strict=Trueoption.
