Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to iterate over multiple lists at once? [duplicate]

Tags:

python

Let's say I have two or more lists of same length. What's a good way to iterate through them?

a, b are the lists.

 for i, ele in enumerate(a):
    print ele, b[i]

or

for i in range(len(a)):
   print a[i], b[i]

or is there any variant I am missing?

Is there any particular advantages of using one over other?

like image 443
frazman Avatar asked Apr 09 '12 21:04

frazman


People also ask

Which type of loop is most effective to iterate over a list?

Using an iterator, or using a foreach loop (which internally uses an iterator), guarantees that the most appropriate way of iterating is used, because the iterator knows about how the list is implemented and how best go from one element to the next.


2 Answers

The usual way is to use zip():

for x, y in zip(a, b):
    # x is from a, y is from b

This will stop when the shorter of the two iterables a and b is exhausted. Also worth noting: itertools.izip() (Python 2 only) and itertools.izip_longest() (itertools.zip_longest() in Python 3).

like image 89
Sven Marnach Avatar answered Oct 06 '22 07:10

Sven Marnach


You can use zip:

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
...   print x, y
... 
1 a
2 b
3 c
like image 23
Rachel Shallit Avatar answered Oct 06 '22 07:10

Rachel Shallit