Syntax for simultaneous "for" loops?

Laura Creighton lac at strakt.com
Mon Feb 17 06:50:15 EST 2003


In a message of Mon, 17 Feb 2003 11:26:38 GMT, Padraig at Linux.ie writes:
>John Ladasky wrote:
>> Hi there,
>> 
>> A few weeks ago I was agonizing over choosing a new programming
>> language, after not having programmed for years.
>> 
>> http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=c09b237b.030206
>0136.5683054e%40posting.google.com
>> 
>> I appear to have chosen Python.  I am really pleased with how quickly
>> I am getting results.
>> 
>> A few days ago I came across a web page which described a "for"
>> syntax, which allowed two variables to be stepped at the same time,
>> through two independent lists.  I said to myself, "that's cool, I
>> wonder when I might need that?"  Well, I need it now.  But I
>> bookmarked the relevant web page at work, and we're snowed in here!
>> 
>> Would some kind soul please point me to the relevant information? 
>> Thanks!
>
>You probably want to use zip() in conjunction with tuple expansion:
>
>l1=["a",'b','c']
>l2=[1,2,3]
>for one, two in zip(l1,l2):
>     print one, two
>
>Pádraig.

Note, that zip returns a list of tuples, so if you have some other way
of generating a list of tuples, you can just drop that in.  In particular,
since zip _truncates_ to the shortest list, this is a useful idiom:

_indices = xrange(sys.maxint) 
for index, value in zip(_indices, someList):
    whatever_you_want()

This will give you indices 1,2,3, ... to however long someList is.

Sometimes, however, the truncating behaviour is not what you want.
You'd be happier if the shorter list were padded with 'None' to be
as long as the longer list.  Then you use map:

>>> l1=[1,2,3]
>>> l2=['a','b','c','d','e']
>>> zip(l1,l2)
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> map(None, l1, l2)
[(1, 'a'), (2, 'b'), (3, 'c'), (None, 'd'), (None, 'e')]

Note that map is much more useful than this.  See the manual for more.
Note also that the 'None' argument to map does _not_ specify what to
pad with.

>>> map(33,l1,l2) # this doesn't pad with 33 instead of None
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: object of type 'int' is not callable

HTH,
Laura Creighton





More information about the Python-list mailing list