Python zip function Explained [Easy Examples]

 

Introduction to Python zip function

Python has a number of built-in functions that allow coders to loop through data. One of these functions is the Python zip function. The zip function creates an iterator that merges elements from two or more data sources into one. In this tutorial, we will learn about the Python zip function. We will cover different scenarios including passing no arguments, one argument, and multiple arguments to the zip function.

We will also learn how the zip function works with different data set including lists, strings, sets, and dictionaries by taking various examples. Moreover, we will use the zip function to unzip the zipped objects as well. In a nutshell, this tutorial will contain all the necessary information and examples that you need to know in order to start working with the Python zip function.

Advertisement

 

Getting started with Python zip function

As we already discussed that the Python zip function accepts iterable items and merges them into a single tuple. The resultant value is a zip object that stores pairs of iterables. We can pass lists, tuples, sets, or dictionaries through the zip function. The simple syntax of the python zip function is as follows:

zip(*iterables)
# or
zip(iterator_1, iterqator_2, iterator_3 ...)

Notice that the zip function can take any number of iterators as an argument. There is no fixed number. If no parameters are passed on the zip function then, it returns the empty iterator. If a single iterable is passed to the zip function, then it returns the iterator of 1-tuples. Meaning, the number of items in each tuple will be 1.

 

Checking zip object in Python

If we use the python zip function with n arguments, then that function will return the iterator that generates tuples of length n. We can use the Python type() function to determine its type. See the example below:

# creating lists
num = [1, 2, 3, 4, 5]
characters = ['a', 'b', 'c', 'd']
# applying python zip function
My_zipped_tuple = zip(num, characters)
# checking the type of zipped 
print(type(My_zipped_tuple))

Output:

<class 'zip'>

Notice that the type of object returned by the zip function is zip.

 

Passing no arguments to Python zip function

As we already discussed that the python zip function can take any number of arguments, even we can call the function without passing any arguments. When we call the zip function without any arguments, then our zipped variable holds an empty iterator. If we consume the iterator with a list, we can see an empty list. Now let us take an example of the python zip function without any arguments. See the example below:

Advertisement
# calling the zip function without any arguments
My_zipped_variable = zip()
# printing the zipped variable
print(list(My_zipped_variable))

Output:

[]

As expected, we get an empty list, because when we call the zip function without any argument, it returns an empty iterator.

 

Passing one argument to the Python zip function

Python zip function can also take just one argument and returns an iterator that yields a series of 1-item tuples. Let us take an example and pass only one argument to the zip function. See the example below:

# Creating list integer values
My_list = [1, 2, 3, 4, 5]
# calling zip function with one argument
My_zipped_variable = zip(My_list)
# creating list of the zipped object
zipped_list = list(My_zipped_variable)
# printing 
print(zipped_list)

Output:

[(1,), (2,), (3,), (4,), (5,)]

The number of tuples will be equal to the number of elements of the provided argument.

 

Passing multiple arguments to the python zip function

We can also pass multiple arguments to the zip function. Then the number of tuples returned by the function will be equal to the length of the provided iterable which has the smallest length.  Let us take an example and pass multiple arguments to the zip function. See the example below:

# Creating list integer values
My_list1 = [1, 2, 3, 4, 5]
My_list2 = ['a', 'b', 'c']
My_list3 = ['Age', 'name', 'city', 'country']
# calling zip function with multiple arguments
My_zipped_variable = zip(My_list1, My_list2, My_list3)
# creating list of the zipped object
zipped_list = list(My_zipped_variable)
# printing 
print(zipped_list)

Output:

[(1, 'a', 'Age'), (2, 'b', 'name'), (3, 'c', 'city')]

Notice that the length of each of the tuples is 3 because it was the smallest length among provided iterators.

Advertisement

 

Python zip function and strings as an arguments

In Python, the string is an immutable sequence data type. It is the sequence of Unicode characters wrapped inside single, double, or triple quotes. In this section, we will provide strings as an argument to the zip function. See the example below:

 

Example of Python zip function with strings

Now let us take an example of the zip function which takes strings as an argument. See the python program below:

# defining strings types
string1 = "Go"
string2 = "linux"
string3 = "cloud"
# calling zip function with string arguments
zipped_variable = zip(string1, string2, string3)
# printing
print(list(zipped_variable))

Output:

[('G', 'l', 'c'), ('o', 'i', 'l')]

Notice that the zip function is taking the first elements from each of the iterators and then putting them in a single tuple as shown in the above example.

 

Python zip function and sets as an arguments

A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Python's set class represents the mathematical notion of a set. Since sets are unordered, we cannot access items using indexes as we do in lists. In this section, we will use sets as arguments in the python zip function.

 

Example of Python zip function with sets

Now let us take an example and pass python sets as arguments to the zip function. See the Python program below:

# defining sets
set1 = {1, 2, 3, 4, 5}
set2 = {'a', 'b', 'c', 'd'}
set3 = {"name", "Age", "city"}
# calling zip function with set arguments
zipped_variable = zip(set1, set2, set3)
# printing
print(list(zipped_variable))

Output:

[(1, 'c', 'Age'), (2, 'a', 'name'), (3, 'd', 'city')]

Notice that the zip function has iterated through the elements of the provided arguments and then returned tuples containing the elements from each of the iterators.

Advertisement

 

Python zip function and lists as arguments

A list is an ordered and mutable Python container, being one of the most common data structures in Python. Unlike sets, it can contain duplicate elements as well. In python, the square brackets([]) are used to declare lists. In this section, we will use lists as arguments in the zip function. 

 

Example of Python zip function with lists

Now let us take an example and see how we can use lists as arguments in the python zip function. See the example below:

# defining python lists
list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c', 'd']
list3 = ["name", "Age", "city"]
# calling zip function with list arguments
zipped_variable = zip(list1, list2, list3)
# printing
print(list(zipped_variable))

Output:

[(1, 'a', 'name'), (2, 'b', 'Age'), (3, 'c', 'city')]

Notice that we have used lists as arguments in the zip function and it takes the elements from each of the lists and returns tuples.

 

Unzipping the values using the Python zip function

We can also extract the data from the Python zip function. If we want to remove the zip, we have to use the same zip function with an asterisk(*) in front of that list we get from the zipped variable. For example, see the python program below, which first applies the zip function on given iterators and then unzip it using the same function.

# defining python lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = ['name', 'age', 'city']
# calling zip function with list arguments
zipped_variable = zip(list1, list2, list3)
#  unzipped variable using zip function
x, y, z = zip(*zipped_variable )
# printing 
print("The unzipped variables contains: ")
print('list1 = ', x)
print('list2 = ', y)
print('list3 = ', z)

Output:

The unzipped variables contains:
list1 = (1, 2, 3)
list2 = ('a', 'b', 'c')
list3 = ('name', 'age', 'city')

In the program above, we first converted the iterators into zipped values and then unzipped the variable using the same function along with an asterisk in the beginning. One of the disadvantages of unzipping is that we might lose some value. For example, see the python program below:

# defining python lists
list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c']
list3 = ['name', 'age', 'city']
# calling zip function with list arguments
zipped_variable = zip(list1, list2, list3)
#  unzipped variable using zip function
x, y, z = zip(*zipped_variable )
# printing 
print("The unzipped variables contains: ")
print('list1 = ', x)
print('list2 = ', y)
print('list3 = ', z)

Output:

The unzipped variables contains:
list1 = (1, 2, 3)
list2 = ('a', 'b', 'c')
list3 = ('name', 'age', 'city')

Notice that our list1 contains 5 values but when we unzipped it, we only get the first 3 and the rest were ignored. Because the zip function only considers the three values as it was the smallest length among iterators.

 

Looping over iterables and the python zip function

A Python for loop iterates over an object until that object is complete. The two most common types of loops are while loop and for loop. You can read more about them from the articles Python while loop and python for loop respectively. Here we will use Python for loop to iterate over the iterable.

 

Traversing lists using Python zip function

The zip function allows us to iterate in parallel over two or more iterables. Since the zip function generates tuples, we can unpack these in the header of a python for loop. See the example below:

# defining python lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = ['name', 'age', 'city']
# calling zip function with list arguments
zipped_variable = zip(list1, list2, list3)
# for loop to iterate
for x, y, z in zipped_variable:
    print(x, y, z)

Output:

1 a name
2 b age
3 c city

In the program above, we first apply the zip function on multiple lists and then iterate through the zipped values using for loop and print the values.

 

Summary

The Python zip function accepts iterable items and merges them into a single tuple. The resultant value is a zip object that stores pairs of iterables. we can pass different iterables including lists, tuples, sets, or dictionaries through the zip function. In this tutorial, we learned about the python zip function. We discussed the different scenarios by passing no arguments, a single argument, and multiple arguments to the zip function.

We also covered various examples by providing different iterables to the zip function. Moreover, we also unzipped a zipped variable using the same function. To summarize, this tutorial contains all the necessary details and examples that you need to know in order to start working with the python zip function.

 

Further Reading

Python zip function
Python built functions
Python iterators

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment