Velocity Reviews > Iterating two arrays at once

Iterating two arrays at once

mathieu
Guest
Posts: n/a

 08-29-2008
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 !

Bruno Desthuilliers
Guest
Posts: n/a

 08-29-2008
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

Matthias Bläsing
Guest
Posts: n/a

 08-29-2008
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,

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

mathieu
Guest
Posts: n/a

 08-29-2008
On Aug 29, 12:46 pm, Matthias Bläsing <matthias.blaes...@rwth-
aachen.de> wrote:
> 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,
>
>
> 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 !

Bruno Desthuilliers
Guest
Posts: n/a

 08-29-2008
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.

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is OffTrackbacks are On Pingbacks are On Refbacks are Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post PerlFAQ Server Perl Misc 0 02-02-2011 05:00 AM carl C++ 5 11-25-2009 09:55 AM mh@pixar.com Python 4 08-29-2008 01:47 PM Kev Jackson Ruby 2 03-29-2006 03:58 PM Dan Python 3 07-25-2004 07:19 PM