27

Is there a way in python to forloop over two or more lists simultaneously?

Something like

a = [1,2,3]
b = [4,5,6]
for x,y in a,b:
    print x,y

to output

1 4
2 5
3 6

I know that I can do it with tuples like

l = [(1,4), (2,5), (3,6)]
for x,y in l:
    print x,y
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user80551
  • 1,134
  • 2
  • 15
  • 26

1 Answers1

70

You can use the zip() function to pair up lists:

for x, y in zip(a, b):

Demo:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> for x, y in zip(a, b):
...     print x, y
... 
1 4
2 5
3 6
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 2
    @ilamengl: if you are going to alter answers from Python 2 to Python 3 syntax or documentation references, then do so for the question as well. Since this question is tagged, explicitly, with the `python-2.7` tag I'm reverting your edit, as it is *not applicable here*. – Martijn Pieters May 23 '21 at 13:34
  • Python 2 support has ended, yes, but that doesn't mean that there is no one still using it. Always check the tags when reading answers, please do not change tags. – Martijn Pieters May 23 '21 at 14:30