looping over more than one list

Iain King iainking at gmail.com
Thu Feb 16 10:00:47 EST 2006


When I loop over one list I use:

for item in items:
    print item

but often I want to loop through two lists at once, and I've been doing
this like I would in any other language - creating an index counter and
incrementing it.
For example, (completely arbitrary), I have two strings of the same
length, and I want to return a string which, at each character
position, has the letter closest to 'A' from each of the original
strings:

def lowest(s1,s2):
    s = ""
    for i in xrange(len(s1)):
        s += lowerChar(s1[i],s2[i])
    return s

this seems unpythonic, compared to something like:

def lowest(s1,s2):
    s = ""
    for c1,c2 in s1,s2:
        s += lowerChar(c1,c2)
    return s

this doesn't work - s1,s2 becomes a tuple.  Is there a way to do this
that I'm missing?  I don't see it in the docs.

This works:

def lowest(s1,s2):
    s = ""
    for c1,c2 in [x for x in zip(s1,s2)]:
        s += lowerChar(c1,c2)
    return s

but it's hardly any more elegant than using a loop counter, and I'm
guessing it's performance is a lot worse - I assume that the zip
operation is extra work?

Iain




More information about the Python-list mailing list