Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python iterate over two lists simultaneously [duplicate]

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
like image 769
user80551 Avatar asked Jan 13 '14 18:01

user80551


1 Answers

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
like image 109
Martijn Pieters Avatar answered Nov 16 '22 02:11

Martijn Pieters