Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Iterate through 2 lists at the same time [duplicate]

Tags:

python

loops

list

Possible Duplicate:
How to iterate through two lists in parallel?

I have 2 lists:

l = ["a", "b", "c"]
m = ["x", "y", "z"]

And I want to iterate through both at the same time, something like this:

for e, f in l, m:
    print e, f

Must show:

a x
b y
c z

The thing is that is totally illegal. How can I do something like this? (In a Pythonic way)

like image 858
Lucas Gabriel Sánchez Avatar asked May 24 '26 01:05

Lucas Gabriel Sánchez


1 Answers

Look at itertools izip. It'll look like this

for i,j in izip( mylistA, mylistB ):
    print i + j

The zip function will also work but izip creates an iterator which does not force the creation of a third list.

like image 55
wheaties Avatar answered May 25 '26 14:05

wheaties



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!