Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the pythonic way to loop through two arrays at the same time?

Tags:

python

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?

like image 626
will Avatar asked Jan 12 '13 13:01

will


People also ask

How do you iterate two arrays in Python?

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.

Are for loops Pythonic?

💡 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.


2 Answers

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:

  • from future_builtin import zip -- if you wish to program with Python3-style zip while in Python2.
  • itertools.izip_longest -- if a and b are of unequal length.
like image 138
unutbu Avatar answered Oct 18 '22 10:10

unutbu


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.

like image 27
Vincenzo Pii Avatar answered Oct 18 '22 09:10

Vincenzo Pii