71

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?

nbro
  • 15,395
  • 32
  • 113
  • 196
frazman
  • 32,081
  • 75
  • 184
  • 269

2 Answers2

143

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

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 6
    Beat me to it. It may be worth noting that Python 3's `zip` *is* `izip`. Also, there's no `zip_longest` but `map(None, a, b)` can do. – ephemient Apr 09 '12 at 21:57
  • 3
    @ephemient: The latter only on Python 2, again. On Python 3, this will stop on the shortest sequence. And `izip_longest()` is called `zip_longest()` on Python 3… – Sven Marnach Apr 09 '12 at 22:01
  • @SvenMarnach But zip stops when one of the 2 lists end , What if I want to iterate to the max length in python3 – Abhay Jun 27 '18 at 08:01
  • @Abhay That is actually answered above as well – you need to use `iterloos.zip_longest()`. – Sven Marnach Jul 03 '18 at 10:13
16

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
Rachel Shallit
  • 2,002
  • 14
  • 15