Iterating two arrays at once

M

mathieu

Hi there,

just trying to figure out how to iterate over two array without
computing the len of the array:

A = [1,2,3]
B = [4,5,6]
for a,b in A,B: # does not work !
print a,b

It should print:

1,4
2,5
3,6

Thanks !
 
B

Bruno Desthuilliers

mathieu a écrit :
Hi there,

just trying to figure out how to iterate over two array without
computing the len of the array:

A = [1,2,3]
B = [4,5,6]
for a,b in A,B: # does not work !
print a,b

It should print:

1,4
2,5
3,6

for a, b in zip(A, B):
print a, b

or, using itertools (which might be a good idea if your lists are a bit
huge):

from itertools import izip
for a, b in izip(A, B):
print a, b
 
M

Matthias Bläsing

Am Fri, 29 Aug 2008 03:35:51 -0700 schrieb mathieu:>
A = [1,2,3]
B = [4,5,6]
for a,b in A,B: # does not work !
print a,b

It should print:

1,4
2,5
3,6

Hey,

zip is your friend:

for a,b in zip(A,B):
print a,b

does what you want. If you deal with big lists, you can use izip from
itertools, which returns a generator.

from itertools import izip
for a,b in izip(A,B):
print a,b

HTH

Matthias
 
M

mathieu

Am Fri, 29 Aug 2008 03:35:51 -0700 schrieb mathieu:>
A = [1,2,3]
B = [4,5,6]
for a,b in A,B: # does not work !
print a,b
It should print:
1,4
2,5
3,6

Hey,

zip is your friend:

for a,b in zip(A,B):
print a,b

does what you want. If you deal with big lists, you can use izip from
itertools, which returns a generator.

from itertools import izip
for a,b in izip(A,B):
print a,b

Thanks all !
 
B

Bruno Desthuilliers

mathieu a écrit :
(snip solution)
Thanks all !

FWIW, this has been discussed here *very* recently (a couple hours ago).
Look for a thread named "iterating over two arrays in parallel?", and
pay special attention to Terry Reedy's answer.
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top