Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more pythonic in a for loop: zip or enumerate?

Which one of these is considered the more pythonic, taking into account scalability and readability? Using enumerate:

group = ['A','B','C']
tag = ['a','b','c']

for idx, x in enumerate(group):
    print(x, tag[idx])

or using zip:

for x, y in zip(group, tag):
    print(x, y)

The reason I ask is that I have been using a mix of both. I should keep to one standard approach, but which should it be?

like image 920
Little Bobby Tables Avatar asked Dec 05 '22 01:12

Little Bobby Tables


1 Answers

No doubt, zip is more pythonic. It doesn't require that you use a variable to store an index (which you don't otherwise need), and using it allows handling the lists uniformly, while with enumerate, you iterate over one list, and index the other list, i.e. non-uniform handling.

However, you should be aware of the caveat that zip runs only up to the shorter of the two lists. To avoid duplicating someone else's answer I'd just include a reference here: someone else's answer.

@user3100115 aptly points out that in python2, you should prefer using itertools.izip over zip, due its lazy nature (faster and more memory efficient). In python3 zip already behaves like py2's izip.

like image 81
shx2 Avatar answered Jan 06 '23 22:01

shx2