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
0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.