iterating over two arrays in parallel?

M

mh

I want to interate over two arrays in parallel, something like this:

a=[1,2,3]
b=[4,5,6]

for i,j in a,b:
print i,j

where i,j would be 1,4, 2,5, 3,6 etc.

Is this possible?

Many TIA!
Mark
 
S

skip

mark> I want to interate over two arrays in parallel, something like this:
mark> a=[1,2,3]
mark> b=[4,5,6]

mark> for i,j in a,b:
mark> print i,j

mark> where i,j would be 1,4, 2,5, 3,6 etc.

a = [1,2,3]
b = [4,5,6]
for (i,j) in zip(a,b):
print i, j

To avoid recreating the entire list you can substitute itertools.izip for
zip.

Skip
 
L

Luis Zarrabeitia

Quoting (e-mail address removed):
I want to interate over two arrays in parallel, something like this:

a=[1,2,3]
b=[4,5,6]

for i,j in a,b:
print i,j

where i,j would be 1,4, 2,5, 3,6 etc.

Is this possible?

Yeap.

===
for i,j in zip(a,b):
print i,j
===

Or better yet (memory wise at least)

===
from itertools import izip

for i,j in izip(a,b):
print i,j
===

("zip" creates a list with the pairs (i,j), izip returns an iterator over the
pairs "i,j")

Are you really from Pixar? Cool

Cheers,
 
T

Terry Reedy

I want to interate over two arrays in parallel, something like this:

a=[1,2,3]
b=[4,5,6]

for i,j in a,b:
print i,j

where i,j would be 1,4, 2,5, 3,6 etc.

Is this possible?

How to fish for yourself:
search 'Python loop two arrays parallel' and second hit with Google is
http://docs.python.org/tut/node7.html
which has this entry
"To loop over two or more sequences at the same time, the entries can be
paired with the zip() function.
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
.... print 'What is your %s? It is %s.' % (q, a)
....
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
"

Or go to the Tutorial directly, expand the chapter headings, and notice
that 5. Data Structures has section 5.6 Looping Techniques.

Indeed, I recommend that you read thru at least the first 9 chapters.

tjr
 
C

Cousin Stanley

I want to interate over two arrays in parallel,
something like this:

a=[1,2,3]
b=[4,5,6]

for i,j in a,b:
print i,j

where i,j would be 1,4, 2,5, 3,6 etc.

Is this possible?

Many TIA!
Mark
.... print ' ' , this
....
(1, 4)
(2, 5)
(3, 6).... print ' ' , i , j
....
1 4
2 5
3 6
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top