Iterating over multiple lists (a newbie question)

Alex Martelli aleaxit at yahoo.com
Thu Jan 4 07:38:56 EST 2001


"Victor Muslin" <victor at prodigy.net> wrote in message
news:3a539f3a.445366109 at localhost...
> This may be rather silly, but I can't think of a clever way...
>
> To traverse a single list the code is:
>
> for item in list:
> print item

Yep; works for any sequence, not just lists.


> However, if there are multiple lists (of the same length) is there a
> cleverer way to do the following:
>
> for i in range(0,len(list1)):
> print list1[i], list2[i]

Just range(len(list1)) will suffice -- the 0 can be left implied.


> I would like something like this (which obviously does not work):
>
> for one,two in list1, list2:
> print one,two

If the two sequences have identical length, and you're using
Python 2, then the simplest approach is to use the new 'zip'
function, which 'zips' two or more sequences into one sequence
of tuples:
    for one, two in zip(list1, list2):
        print one, two

In older Python versions, map (with a first argument of None)
could play a similar role:
    for one, two in map(None, list1, list2):
        print one, two
and it still works today, though zip is clearer.

But zip and map part company when the sequences can differ in
length.  zip just 'truncates' to the shortest one of the
sequences it's given; map(None, &c) 'lengthens' all sequences
to the length of the longest one, using 'None' to stand in
for "missing" items.

Looping over indices, rather than over items directly (a la
'for i in range(len(list1))' etc, may give you more precise
control on what exactly happens for unequal-length sequences.

But in the common case where using the shortest sequence's
length is what you want, looping-over-contents (with zip)
can be much simpler and handier than looping on indices.


Alex






More information about the Python-list mailing list