Python zip() Function

FREE Online Courses: Dive into Knowledge for Free. Learn More!

In the real world, zip is a device that interlocks two things. In Python, the zip() function has a similar meaning. In this article, we will learn the zip() function, unzipping, and the uses of the zip() function. Let us begin with the introduction.

Python zip() function

The zip() is a built-in function that takes one or more iterables as input. It returns an object that contains the elements of the input iterables mapped based on the index. The syntax of this function is:

zip(*iterables)

In the above syntax, the input can be either the built-in iterables (list, string, set, tuple, and ) or user-defined iterables. And the asterisk before the iterable means that we can give any number of arguments. We can either give no argument, one argument, two arguments, and an ‘n’ number of arguments.

The output is an iterator object that contains the values of each iterator mapped by their index. It returns tuples, with each tuple containing mapped elements. Let us discuss more on the function with examples in the further sections.

No Argument

When we do not give any argument, then we get an empty iterator object.

Example of the zip() function with no argument:

for i in zip():
    print(i)

We do not get any output.

We can see that when we try to get the elements of the zip() with no input, we did not get any output. This shows that the iterable is empty.

We are using a for loop to see the values because as said before the output is an object. So, we do not get to see the values, we just get the information about the object when we print the zip() as shown below.

Example of printing zip() function with no argument:

zip()

Output:

<zip object at 0x000002E65C84CF80>

One Argument

When we give a single argument to the function, then it gives tuples each containing a single value of the input iterable. The first tuple has the zeroth element of the iterable, the second tuple has the first element of the iterable, and so on.

Example of zip() function with one argument:

for i in zip([1,3,5,7,9]):
  print(i)

Output:

(1,)
(3,)
(5,)
(7,)
(9,)

We can see that each tuple has a single element.

Multiple Arguments

We can also give more than one argument to the zip() function. Again we get iterable containing tuples. The elements of these arguments get mapped by the index and the values of the same index become the values of a tuple.

We have many cases under this which include:
1. Giving two arguments of the same length
2. Giving two arguments of different length
3. Getting iterable with all the elements of the longest input sequence
4. Giving more than two arguments

We will discuss these cases with examples in this section.

1. Two arguments of the same length:

When we give two iterables of the same length, then we get iterable with tuples holding the mapped values. The mapping as said before is done based on the index.

The first tuple will have the zeroth index values of the two iterables, the second tuple will have the first index values, and so on.

Example of zip() with two arguments of equal length:

for i in zip(('a','b','c','d'),(1,2,3,4)):
  print(i)

Output:

(‘a’, 1)
(‘b’, 2)
(‘c’, 3)
(‘d’, 4)

We can see from the above example that the values of the iterables, here tuples, are mapped by their index and stored in tuples.

2. Two arguments of different lengths:

When we give two iterables of unequal length, then we get iterable with tuples with the values mapped only till all the elements of the shorter iterable are covered. Once all the values of the short sequence are done mapping, then it stops ignoring the other elements of the longer one.

Example of zip() with two arguments of different lengths:

for i in zip('Python',[5,4,3,2,1]):
    print(i)

Output:

(‘P’, 5)
(‘y’, 4)
(‘t’, 3)
(‘h’, 2)
(‘o’, 1)

In the above example, the string is of length 6 and the length of the list is 5. The mapping is done for all the values of the list and the last character of the string is ignored.

3. Using the zip_longest() function:

We saw above that the extra elements of the longer sequence are ignored. But what if we want to take these values into consideration.

We use the zip_longest() function for this purpose. To use this function, first, we need to import it from itertools. Wondering, what will the extra values be mapped to? By default, they get mapped to ‘None’.

Example of zip_longest():

for i in zip_longest({1,2,3,4,5},(1,4,9)):
    print(i)

Output:

(1, 1)
(2, 4)
(3, 9)
(4, None)
(5, None)

We can also give a value to be set rather than ‘None’ for the extra values to be mapped. For example,

Example of zip_longest():

for i in zip_longest(['a','e','i','o','u'],{1,2,3},fillvalue='?'):
    print(i)

Output:

(‘a’, 1)
(‘e’, 2)
(‘i’, 3)
(‘o’, ‘?’)
(‘u’, ‘?’)

4. Passing more than two arguments:

We can pass more than two arguments. Like the length of the inputs decide the number of tuples in the output, the number of arguments passed affects the length of each tuple.

a. As usual, each tuple will have the corresponding elements of the passed iterables mapped based on the index.

b. And based on our preference we can either use zip() or zip_longest() to get only the values up to the shorter sequence or to get all the values of the longest sequence respectively.

Example of zip() and zip_longest() with more than two arguments:

for i in zip('PythonGeeks', [1,2,3,4,5,6],{1.2,3.4,5.7,9.0}):
    print(i)


for i in zip_longest((3,4,8,9.0,2.3),['r','j','afr'],{0:1,2:3,4:5,6:7}):
    print(i)

Output:

(‘P’, 1, 1.2)
(‘y’, 2, 3.4)
(‘t’, 3, 5.7)
(‘h’, 4, 9.0)
(3, ‘r’, 0)
(4, ‘j’, 2)
(8, ‘afr’, 4)
(9.0, None, 6)
(2.3, None, None)

We can see that we can use any number of iterables and in the case of the dictionary, the keys are mapped.

Conversion to Other Data Types

Till now we used the for loop to see the elements of the zip object. There is another way to view the elements and that is to convert them to other data types implicitly. This not only helps in knowing the values but also in using the converted sequences for other applications. The below code shows conversion to other iterables.

Example of conversion of zip to a list:

zp=zip([1,2,3,4,5],[6,7,8,9,0])
list(zp)

Output:

[(1, 6), (2, 7), (3, 8), (4, 9), (5, 0)]

Example of conversion of zip to a tuple:

zp=zip('abcdef',[1,2,3,4])
tuple(zp)

Output:

((‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4))

Example of conversion of zip to a set:

zp=zip([0,4,8,12],(1,2,3,4),'abc')
set(zp)

Output:

{(8, 3, ‘c’), (0, 1, ‘a’), (4, 2, ‘b’)}

Example of conversion of zip to a dict:

zp=zip_longest({0.1,3.4,5.9,2.8,9.5},(0,3,6,3),fillvalue='?')
dict(zp)

Output:

{0.1: 0, 2.8: 3, 3.4: 6, 5.9: 3, 9.5: ‘?’}

Unzipping in Python

Like we could do zipping of values, we can also do unzipping. We do not get the same iterables given as the input, but the tuples the zip object contains. For example,

Example of Python unzipping:

tup1,tup2,tup3,tup4=zip('wxyz',[0,1,2,3])

tup1

tup2

tup3

tup4

Output:

(‘w’, 0)

(‘x’, 1)

(‘y’, 2)

(‘z’, 3)

When we give tuples of unequal length, then the number of variables used while unzipping will be equal to the length of the smallest sequence when we use zip(). But if we use zip_longest(), then the number of variables we give need to be equal to the length of the longest input. For example,

Example of unzipping in Python:

t1,t2,t3=zip([5,9,12,-2],{6,10,12})

t1

t2

t3

Output:

(5, 10)

(9, 12)

(12, 6)

Example of unzipping with zip_longest():

t1,t2,t3,t4,t5=zip_longest('abc',(15,6,4,13,7))

t1

t2

t3

t4

t5

Output:

(‘a’, 15)

(‘b’, 6)

(‘c’, 4)

(None, 13)

(None, 7)

But if we give wrong number of variables, we get an error as shown below.

Example of getting an error on giving wrong count of variables while unzipping:

t1,t2,t3,t4,t5=zip('wfdg',{1,6,9,3})

Output:

Traceback (most recent call last):
File “<pyshell#70>”, line 1, in <module>
t1,t2,t3,t4,t5=zip(‘wfdg’,{1,6,9,3})
ValueError: not enough values to unpack (expected 5, got 4)

Applications of Python Zip() Function

The zip object obtained from the zip() function is has many applications, which include:

1. Parallel traversal and soring of the list: When we want to store the elements based on the order of one of the input iterables, we can use the sorted() function, to get the analysis.

2. Processing the corresponding values from multiple sequences: When we have the two different values stored in two sequences and we want to produce the results based on the values of both sequences, then we can zip and process them.

We will see examples of these applications in the next section of interview questions.

Interview Questions on Python zip() function:

Q1. Given a list and a set. The set stores the id values of the students and the list stores the section. Find the number of students to whose section is not found.

Ans. We can use the zip_longest() function and find the number of None values.

Example of zip_longest() and counting None values:

set1={1,2,3,4,5,6,7,8,9,10}
lista=['A','A','B',None,'C','B','A']

cnt=0
for iD,sec in zip_longest(set1,lista):
    if(sec==None):
        cnt=cnt+1

cnt

Output:

4

Q2. Given a list of items and their prices in two lists. Provide a list containing the item names and corresponding prices in the increasing order of prices.

Ans. We can zip the prices and items and convert them to a list and use the sorted() function to sort according to the price.

Example of sorting the list:

items=['It1','It2','It3','It4','It5']
prices=[54,78,93,103,60]

sorted(list(zip(prices,items)))

Output:

[(54, ‘It1’), (60, ‘It5’), (78, ‘It2’), (93, ‘It3’), (103, ‘It4’)]

Q3. Given the values in a list and the corresponding weights in another list. Find the contribution of each value and also the total contribution.

Ans. Below is the example of processing the values in zip:

vals=[3,8,19,34]
wts=[4,9,-1,2]
ttl=0
for v,w in zip(vals,wts):
    ttl=ttl+v*w
    print(f"The contribution of {v} is {v*w}")

print("Total weighted sum:",ttl)

Output:

The contribution of 3 is 12
The contribution of 8 is 72
The contribution of 19 is -19
The contribution of 34 is 68
Total weighted sum: 133

Q4. Write a function to store the username, Gmail, password of the user together.
Ans. Below is the example of zip() with three arguments:

name=['abc','xyz','pqr','trew']
mail=['[email protected]','[email protected]','[email protected]','[email protected]']
pas=['23','fetr','43pr','pr34','tre56']

list(zip(name,mail,pas))

Output:

[(‘abc’, ‘[email protected]’, ’23’), (‘xyz’, ‘[email protected]’, ‘fetr’), (‘pqr’, ‘[email protected]’, ’43pr’), (‘trew’, ‘[email protected]’, ‘pr34’)]

Q5. Write a function to unzip the values of employees and their corresponding salaries.
Ans. Below is the example of unzipping in Python:

emp=['A','B','C','D','E']
sal_th=(40,55,70,35,105)

for e,sa in zip(emp,sal_th):
    print(f"The salary of employee {e} is {sa}")

Output:

The salary of employee A is 40
The salary of employee B is 55
The salary of employee C is 70
The salary of employee D is 35
The salary of employee E is 105

Quiz on Zip() Function in Python

Conclusion

Hoping that you understood the concepts discussed in this article. To revise, we first got introduced to the zip() function, the arguments, conversion to other data types. Then we saw unzipping and its application.
Finally, we saw some interview questions. Hoping to see you again at some other or the same article. Happy learning!

If you are Happy with PythonGeeks, do not forget to make us happy with your positive feedback on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *