Python Zip Two Lists [3+ Best Methods with Code Examples]
Table of Contents
Introduction to Python Zip Two Lists
- The concept of combining two or more lists into a single list object changing the dimensions of the original list is known as zipping.
- In the case of two lists, you can use zipping to combine them element-wise, creating a new iterable of tuples containing the elements of both lists at the same index. The resulting list will have a length equal to the original list but dimensions will be different.
Table of Contents
Zipping two list of same lengths
Using the zip() function
The Python built-in zip() function creates an iterator that concatenates elements from each of the lists passed as arguments.
It returns a zip object, which can be converted into a list, tuple or set.
For Example:
users = ["John" , "Mark" , "Goom"]
age = [20 , 25 ,28]
combined_list = list(zip(users , age))
print(combined_list)
Output:
[('John', 20), ('Mark', 25), ('Goom', 28)]
here we have combined two different (3×1) list with user name and age into single (3×2) list
Using a list comprehension
List comprehension is a simple way to create lists. You can use it to iterate over two lists and create a new list of tuples containing elements from both lists.
We can achieve zipping of lists using a list comprehension, which allows us to iterate over the indices of the lists and combine their elements into tuples.
For example –
users = ["John" , "Mark" , "Goom"]
age = [20 , 25 ,28]
combined_list = [(users[i], age[i]) for i in range(len(users))]
print(combined_list)
Output:
[('John', 20), ('Mark', 25), ('Goom', 28)]
Using the map() function
The built-in map() function applies a function to each element of a list. In this function you can use it to map the built-in tuple() function to each pair of elements from the two lists.
users = ["John" , "Mark" , "Goom"]
age = [20 , 25 ,28]
combined_list = list(map(tuple, zip(users, age)))
print(combined_list)
Output:
[('John', 20), ('Mark', 25), ('Goom', 28)]
Zip More than two lists
Using zip() method
We can use the same zip() method to combine more than 2 lists into a single one.
For Example –
students = ["Goom" , "Tim" , "Ash"]
subjects = ["English" , "Physics" , "Chemistry"]
grades = [100 ,40 ,80]
result = ["Pass" , "Fail" , "Pass"]
combined_list = list(zip(students , subjects , grades ,result ))
print(combined_list)
Ouptut:
[('Goom', 'English', 100, 'Pass'), ('Tim', 'Physics', 40, 'Fail'), ('Ash', 'Chemistry', 80, 'Pass')]
Zip lists with different Lengths
Using cycle() method
The cycle() method can be used to pair up characters from a short sequence with characters in a long sequence. Normally zip() will stop when it reaches the end of the short sequence and end iteration there.
For Example –
from itertools import cycle
list1 = ["one" , "two"]
list2 = [10 ,20 ,30 , 40 ,50]
combined_list = list(zip(cycle(list1) , list2 ))
print(combined_list)
[('one', 10), ('two', 20), ('one', 30), ('two', 40), ('one', 50)]
If we would have used the normal zip method the combined list would have contained only 2 elements but by using cycle on list1 the elements inside the list1 are repeating until the list2 iteration is ended.
Using zip_longest() method
If you want to zip different length lists with fillings for the missing elements, you can use the zip_longest() function from the itertools module in Python. This function is similar to zip(), but allows you to specify a fill value for the missing elements.
For Example –
from itertools import zip_longest
list1 = ["one" , "two"]
list2 = [10 ,20 ,30 , 40 ,50]
combined_list = list(zip_longest(list1 , list2 , fillvalue = "Default"))
print(combined_list)
[('one', 10), ('two', 20), ('Default', 30), ('Default', 40), ('Default', 50)]
Here after iteration of list1 is ended the default value is appended to a later iteration for list2 . this can be done with multiple list also
Precausions to be taken while zipping list
Length Mismatch Error
This error occurs when we try to zip the 2 lists with different lengths. The zip function takes the length of the smaller list and eliminates the rest of the items in the bigger list.
For example –
list_1 = [10 ,20 ]
list_2 = ["One" , "Two" , "Three"]
combined_list = list(zip(list_1, list_2))
print(combined_list)
Output:
[(10, 'One'), (20, 'Two')]
Use Cases
Zip Two Lists into Dictionary
If you have two lists, one containing keys and the other containing values, you can use the zip() function to create a dictionary.
For Example –
items = ["Mobile" , "TV" , "Refrigerator"]
price = [10000 , 30000 , 60000]
final_dict = dict(zip(items , price))
print(final_dict)
Output:
{'Mobile': 10000, 'TV': 30000, 'Refrigerator': 60000}
Transposing a matrix
You can use zip() to transpose a matrix represented as a list of lists.
matrix = [[10, 20 ,30], [40, 50, 60], [70, 80, 90]]
transposed_matrix = list(zip(*matrix))
print(transposed_matrix)
Output:
[(10, 40, 70), (20, 50, 80), (30, 60, 90)]