Introduction to zip function

It is the function which is used to aggregate elements from different iterables into one iterables in such a form that iterables with same index is merge as one.

Let’s look through example, will give better intuition where to use zip.

Suppose, we are having two list and we are aggregating them into one list. Let’s see how.

Creating two list

l1 = [1,2,3,4]
l2 = ['a','b','c','d']

 

Zipping two list

In [2]:
zipped = zip(l1,l2)
Here this zip function in Python3 is returning zip object rather than list. So, in order to access it either convert it to list or use ‘for in’ loop.
 
In [3]:
## It is returning a zip object
zipped
Out[3]:
 

Accessing the elements

In [4]:
for e in zipped:
    print(e)
 
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')

Next() method

In zip function, we also have the next method to access next value. As we have already seen it in generators, enumerate.

In this example, it is showing some error because in the previous step in which we are using ‘for in’ loop to access values and we are reaching till end. So next method is not able to detect any value after that.

In [5]:

## It also has next method to access next value
## Here it is giving error because we accessed till last value. Next values are empty now.


next(zipped)
 
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
 in ()
      3 
      4 
----> 5 next(zipped)

StopIteration:

Zipping for different lengths of iterables

If we are zipping different length iterables then, it will aggregate till the length of shorter iterable.
 
In [6]:
l1 = [1,2,3,4,5]
l2 = ['a','b','c']
zipped_new = zip(l1,l2)
In [7]:
list(zipped_new)
Out[7]:
[(1, 'a'), (2, 'b'), (3, 'c')]

Unzipping

In this unzipping, it is just opposite of what we have done in zipping.

In [8]:
l_a , l_b = zip(* zipped_new)
Here, it is giving error because in the previous step we have accessed till last hence no value to unzip.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
 in ()
----> 1 l_a , l_b = zip(* zipped_new)

ValueError: not enough values to unpack (expected 2, got 0)
Now, if we are creating again zipped list and unzipping it, see it is working fine.
In [9]:
zipped_new = zip(l1,l2)
l_a , l_b = zip(* zipped_new)
In [10]:
l_a, l_b
Out[10]:
((1, 2, 3), ('a', 'b', 'c'))