iterating over lists

Alex Martelli aleaxit at yahoo.com
Sat Jun 2 15:16:00 EDT 2001


"John Hunter" <jdhunter at nitace.bsd.uchicago.edu> wrote in message
news:1rsnhinct5.fsf at video.bsd.uchicago.edu...
> I have three lists of equal size: list1, list2 and list3.
>
> What I want but doesn't work:
>
>   for (x1, x2, x3) in (list1, list2, list3):
>      print x1, x2, x3

It does work, just doesn't do what you want: it's the
same as
    print list1, list2, list3

Note, btw, that all the parentheses you use in this
example are redundant.  I think you'd be better off
in terms of clarity and readability if you did not use
parentheses in this case.


> I know I can do it by keeping a index count variable:
>
>      N = len(list1)
>      for i in range(1,N):
>          print list1[i], list2[i], list3[i]

Almost!  you'd better make the range(0,N) or you'll
miss out on the first item of each list.


> but am wondering if there is way to create a tuple of named variables
> as in the (x1, x2, x3) example above.

Most likely what you want is:
    for x1, x2, x3 in zip(list1, list2, list3):
        print x1, x2, x3
which gives you as many print statements as there are
items in the SHORTEST list (doesn't matter if the lists
are all the same length, of course).  A slightly more
obscure alternative:
    for x1, x2, x3 in map(None, list1, list2, list3):
        print x1, x2, x3
gives you as many print statements as there are items
in the LONGEST list instead, the shorter ones being
virtually padded with copies of None.


> One final question:  If I do:
>
>      for i in range( 1, len(list1) ):
>          print list1[i], list2[i], list3[i]
>
> I assume the len(list1) call will only be evaluated once.  Is this
> correct?

Yes, definitely.  More generally, "for i in <expression>" only
evaluates the expression once (before binding or rebinding i,
but that's only relevant if <expression> uses i:-).


Alex






More information about the Python-list mailing list