Python zip() is a built-in function that takes zero or more iterable objects as arguments (e.g. lists, tuples, or sets) and aggregates them in the form of a series of tuples. It returns a new iterator (zip object) which is a series of tuples where the first element of the tuple is an element of the first input iterable object and the second element of the tuple is an element of the second input. Basically, it returns an iterator that generates tuples containing the elements of each list, paired up based on their position.
In this article, we will discuss the zip() function syntax, parameters, and how to use the zip() function to combine multiple iterable objects into a tuple.
1. Quick Examples of using zip() function
Following are quick examples of using the zip() function.
# Quick Examples of using zip() function
# Initialize two lists
subjects1 = [“Java”,”Python”,”PHP”]
subjects2 = [‘C#’,’CPP’,’C’]
# Example 1: zip() function with out arguments
final = list(zip())
# Example 2: Passing single iterable
final = list(zip(subjects1))
# Example 3: Passing multiple iterable
final = list(zip(subjects1, subjects2))
# Example 4: Unequal list length
subjects1 = [“Java”,”Python”,”PHP”,”html”]
subjects2 = [‘C#’,’CPP’,’C’]
final = list(zip(subjects1, subjects2))
# Example 5: Traversing Parallelly
for i, j in zip(subjects1, subjects2):
print(i,” “,j)
# Example 6: Unzipping
subjects1,subjects2=zip(*final1)
# Example 7: Use zip() to convert the dictionary
keys = [“course”, “fee”, “duration”]
values = [‘Python’,’4000′,’45 days’]
final = zip(keys, values)
2. Python zip() Function Usage
Python zip() is a built-in function that is used to zip or combine the elements from two or more iterable objects like list, tuple, dictionary, etc. For example, if you pass two lists (names and ages) as input to the zip() function, it returns an iterator that generates tuples containing the elements of each list, paired up based on their position. It actually returns a zipped object, to convert it to the list using the list() function.
If we pass different lengths of iterable into the zip() function, it returns the iterable object having the same length of the least-passed iterable object.
2.1 Syntax of zip() Function
Following is the syntax of the zip() function.
# Syntax of zip() function
zip(iterator1,iterator2,…)
2.2 Parameters of zip()
It takes iterable objects as its arguments.
2.3 Return value
It returns a zip object which is the iterable object of tuples.
If no argument is passed into zip(), it will return the empty iterator.
If we pass one argument, it will return the iterable of tuples where each tuple has a single element.
If we pass more than two iterables, it will return an iterable of tuples where each tuple contains elements of all passed iterables.
3. zip() with Two Iterable as Argument
Using two iterable objects to the zip() function is mostly used in Python, this is basically used to zip two lists to combine the elements from the lists into a list of tuples. It will return the iterable of tuples where each tuple has the mapped elements of both passed iterable objects. Make sure you typecast the return object from the zip() function to get a list of tuples.
Let’s see the output by zipping two lists.
# Initialize two lists
subjects1 = [“Java”, “Python”, “PHP”]
subjects2 = [‘C#’,’CPP’,’C’]
print(“List1 :”, subjects1)
print(“List2 :”, subjects2)
# Zip two lists
final = zip(subjects1, subjects2)
print(“Zip Lists”, list(final))
Yields below output.
We can see that both elements from both lists are combined.
4. Pass Multiple Iterables into Python zip()
When we pass multiple iterable objects into the zip() function, it returns the iterable of tuples where each tuple has all the elements of passed iterables.
Let’s see the output by zipping three lists.
# Initialize multiple lists
subjects1 = [“Java”, “Python”, “PHP”]
subjects2 = [‘C#’,’CPP’,’C’]
subjects3 = [‘.net’,’pyspark’,’scala’]
print(“List1 :”, subjects1)
print(“List2 :”, subjects2)
print(“list3:”, subjects3)
# Zip multiple lists
final = zip(subjects1, subjects2, subjects3)
print(“Zip Lists”, list(final))
Yields below output.
5. Pass Unequal Lengths of Iterables
Let’s see the output by zipping two lists of unequal lengths. In this case, the extra element will not be included. That means when we pass the unequal length of iterables into zip() function, it will return the iterable of tuples having same length of least passed iterable.
# #Initialize the unequal lengths of list
subjects1 = [“Java”,”Python”,”PHP”,”html”]
subjects2 = [‘C#’,’CPP’,’C’]
print(“List1:”, subjects1)
print(“List2:”, subjects2)
# Zip the unequal lists
final = zip(subjects1, subjects2)
print(“zip unequal lists:”, list(final))
# Output:
# List1: [‘Java’, ‘Python’, ‘PHP’, ‘html’]
# List2: [‘C#’, ‘CPP’, ‘C’]
# zip unequal lists: [(‘Java’, ‘C#’), (‘Python’, ‘CPP’), (‘PHP’, ‘C’)]
Here, “html” is the extra element.
Let’s use loop and traverse both the zipped lists parallelly.
# Traversing Parallelly
print(“List1:”, subjects1)
print(“list2:”, subjects2)
for i, j in zip(subjects1, subjects2):
print(i,” “,j)
# Output:
# List1: [‘Java’, ‘Python’, ‘PHP’]
# List2: [‘C#’, ‘CPP’, ‘C’]
# Java C#
# Python CPP
# PHP C
6. Using zip() Function without Arguments
As you learned above, the zip() function can take more iterable arguments however, you can also use this function without arguments. let’s see an example.
# zip() with out arguments
final = zip()
print(list(final))
# Output:
# []
An empty list is returned.
7. zip() with Single Iterable as Argument
When you pass a single iterable into zip() function, it will return the iterable of tuples having elements of the passed iterable. Finally using typecasting we can get the list of tuples. Let’s pass the single list object to the zip() function and see what it returns.
subjects1 = [“Java”, “Python”, “PHP”]
# Passing single iterable into zip()
final = zip(subjects1)
print(list(final))
# Output:
# [(‘Java’,), (‘Python’,), (‘PHP’,)]
As you see, after type casting it returns the list of tuples. The first element of each tuple contains the element from the list.
8. Unzipping the Iterables
unpack operator (*) is used to unzip the iterable objects. If we pass the unpacking operator inside the zip, then iterators will be unzipped.
Syntax:
# zip() with unpack operator
zip(*zipped_data)
Example: Let’s unzip the above-zipped list.
# Initialize the lists
subjects1 = [“Java”, “Python”, “PHP”, “html”]
subjects2 = [‘C#’,’CPP’,’C’]
final = zip(subjects1, subjects2)
final1 = list(final)
# Unzipping the zipped object
subjects1,subjects2=zip(*final1)
print(“List1:”, subjects1)
print(“List2:”, subjects2)
# Output:
# List1: (‘Java’, ‘Python’, ‘PHP’)
# List2: (‘C#’, ‘CPP’, ‘C’)
9. Zip iterable Objects into Python Dictionary
Moreover, we can use the zip() function to combine two or more iterable objects into a single dictionary in Python. As we know from the above, when we pass two or more iterable objects into the zip() function, it will return the series of tuples. Then using type casting we can convert them into specified data type. Here, I will convert a resultant iterable object into the dictionary.
Related: Python Zip Dictionaries with Examples
Note: When we want to convert dict using zip() we should take the same length of iterable objects otherwise ValueError will be raised.
# Initialize the lists
keys = [“course”, “fee”, “duration”]
values = [‘Python’,’4000′,’45 days’]
print(“List1:”, keys)
print(“List2:”, values)
# Use zip() to convert the dictionary
final = dict(zip(keys, values))
print(“Get the dictionary using zip():n”, final)
# Output:
# List1: [‘course’, ‘fee’, ‘duration’]
# List2: [‘Python’, ‘4000’, ’45 days’]
# Get the dictionary using zip():
# {‘course’: ‘Python’, ‘fee’: ‘4000’, ‘duration’: ’45 days’}
10. Conclusion
In this article, you have learned the Python zip() function Syntax, Parameters, and return type. Also, learned how to use the zip() with no arguments, single argument, and multiple arguments, and finally use zip() with unpack operator.
Happy Learning!!
Python zip() is a built-in function that takes zero or more iterable objects as arguments (e.g. lists, tuples, or sets) and aggregates them in the form of a series of tuples. It returns a new iterator (zip object) which is a series of tuples where the first element of the tuple is an element of the Read More Python, Python Tutorial, Python Builtin Functions