Python Zip & Enumerate Functions

Python Zip and Enumerate Function, Exceptions in Zip, Use of Enumerate Function, Bonus Tip - Using both zip and enumerate together.

Zip Function:

When there are 2 lists and we need to iterator over both the lists parallelly, we can use the zip function.

Lets understand Zip function using the below example.

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

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

Here, notice that we have used 2 variables for iteration. i and j.

“i” will be assigned with the items from “a” and “j” will be assigned with the items from “b” respectively.

Exceptions in Zip:

if only one variable is provided instead of i and j, then NameError will be raised.

for obj in zip(a,b):
    print(obj)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-4323aa7a8932> in <module>
----> 1 for obj in zip(a,b):
      2     print(obj)

NameError: name 'a' is not defined

Another Example:

Lets create a Tuple from 2 lists.

names = ['cat','dog','fox','lion']
index = [1,2,3,4]
with_index = list(zip(names,index))
print(with_index)
[('cat', 1), ('dog', 2), ('fox', 3), ('lion', 4)]

Enumerate Function:

The Enumerate function provides an ability to use the counter value of the iteration.

Using this function, we can use an index of the item as a counter.

a = [20,40,50,60]
b=[6,7,8,9,10]
  
for index,a in enumerate(a):
    print("Index of",a,"is",index)
Index of 20 is 0
Index of 40 is 1
Index of 50 is 2
Index of 60 is 3

Bonus Tip – Using both zip and enumerate together:

a = [20,40,50,60]
b=[6,7,8,9,10]

for index,(a,b) in enumerate(zip(a,b)):
    print(index, (a*b))
0 120
1 280
2 400
3 540

Asha Ponraj
Asha Ponraj

Data science and Machine Learning enthusiast | Software Developer | Blog Writter

Articles: 86

Leave a Reply

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