If I have two arrays, of the same length - say a
and b
a = [4,6,2,6,7,3,6,7,2,5]
b = [6,4,6,3,2,7,8,5,3,5]
normally, I would do this like so:
for i in range(len(a)): print a[i] + b[i]
rather than something like this:
i=0 for number in a: print number + b[i] i += 1
because I prefer to be consistent with methods used.
I know of zip
, but I never use it. Is this what zip
was made for?
would
for pair in zip(a,b): print pair[0] + pair[1]
be the pythonic way to do this?
Use the izip() Function to Iterate Over Two Lists in Python It iterates over the lists until the smallest of them gets exhausted. It then zips or maps the elements of both lists together and returns an iterator object. It returns the elements of both lists mapped together according to their index.
💡 Python's “for” loops are “for-each” loops I would consider this solution to be quite Pythonic. It's nice and clean and almost reads like pseudo code from a text book. I don't have to keep track of the container's size or a running index to access elements.
If the lists a
and b
are short, use zip (as @Vincenzo Pii showed):
for x, y in zip(a, b): print(x + y)
If the lists a
and b
are long, then use itertools.izip to save memory:
import itertools as IT for x, y in IT.izip(a, b): print(x + y)
zip
creates a list of tuples. This can be burdensome (memory-wise) if a
and b
are large.
itertools.izip
returns an iterator. The iterator does not generate the complete list of tuples; it only yields each item as it is requested by the for-loop. Thus it can save you some memory.
In Python2 calling zip(a,b)
on short lists is quicker than using itertools.izip(a,b)
. But in Python3 note that zip
returns an iterator by default (i.e. it is equivalent to itertools.izip
in Python2).
Other variants of interest:
zip
while in Python2.a
and b
are of unequal length.A possible solution is using zip
, as you mentioned yourself, but slightly differently than how you wrote it in the question:
for x, y in zip(a, b): print x, y
Notice that the length of the list of tuples returned by zip()
will be equal to the minimum between the lengths of a
and b
. This impacts when a
and b
are not of the same length.
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