Zip Two Lists Together in Python
In Python, the zip()
function is used to combine two or more lists element-wise, creating tuples containing elements from corresponding positions in the input lists.
Examples
1. Using zip()
to Combine Two Lists
The zip()
function pairs corresponding elements from two lists into tuples.
</>
Copy
# Defining two lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
# Zipping the two lists together
zipped_list = list(zip(names, ages))
# Printing the zipped list
print("Zipped List:", zipped_list)
In this example:
names
is a list containing three names.ages
is a list containing three corresponding ages.- The
zip()
function pairs elements at the same index from both lists into tuples. - The
list()
function converts the zip object into a readable list.
Output:
Zipped List: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
2. Using zip()
in a Loop
We can use zip()
inside a For loop to iterate over two lists simultaneously.
</>
Copy
# Defining two lists
cities = ["New York", "Paris", "Tokyo"]
countries = ["USA", "France", "Japan"]
# Iterating using zip
for city, country in zip(cities, countries):
print(f"{city} is in {country}")
Here:
cities
is a list of city names.countries
is a list of country names.zip()
pairs city-country values and the loop prints them in a sentence format.
Output:
New York is in USA
Paris is in France
Tokyo is in Japan
3. Zipping Lists of Unequal Length
If the lists are of unequal length, zip()
stops at the shortest list.
</>
Copy
# Defining two lists of different lengths
students = ["John", "Emma", "Liam", "Olivia"]
scores = [85, 90, 78]
# Zipping the lists
zipped_data = list(zip(students, scores))
# Printing the result
print("Zipped Data:", zipped_data)
In this case:
- The
students
list has four elements, butscores
has only three. zip()
stops at the third element, ignoring the extra student.
Output:
Zipped Data: [('John', 85), ('Emma', 90), ('Liam', 78)]
4. Unzipping a Zipped List
We can use the *
operator to unzip a zipped list back into separate lists.
</>
Copy
# Zipping two lists
products = ["Laptop", "Phone", "Tablet"]
prices = [1200, 800, 500]
zipped = zip(products, prices)
# Unzipping the lists
unzipped_products, unzipped_prices = zip(*zipped)
# Printing results
print("Products:", list(unzipped_products))
print("Prices:", list(unzipped_prices))
Here:
- The
*
operator unpacks the tuples inside the zipped object. - The original lists are retrieved by using
zip(*zipped)
.
Output:
Products: ['Laptop', 'Phone', 'Tablet']
Prices: [1200, 800, 500]
Conclusion
The zip()
function is a powerful way to pair elements from multiple lists in Python. Here are key takeaways:
zip()
combines two lists element-wise into tuples.- It can be used in loops for parallel iteration.
- If lists are of unequal length, it stops at the shortest one.
- We can unzip a zipped list using
zip(*zipped_list)
.