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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With