Looping on more than one list

David Goodger dgoodger at bigfoot.com
Sun Jul 23 00:48:50 EDT 2000


on 2000-07-22 12:08, ahmed Bouferguene (aboufer at atlsci.com) wrote:
> Do no know much of python, but I am wondering whether it is possible
> to loop
> on more than one list

A more elegant solution is currently in the works, but for now, you can use:

>>> map(None,"abcd",[1,2,3])
[('a', 1), ('b', 2), ('c', 3), ('d', None)]

"abcd" is a sequence of 4 items, of course. The above doesn't stop on
exhaustion of the shortest list though. If it must, you can use:

>>> a = [1,2,34]
>>> b=["a", "b", "d"]
>>> for (x,y) in map(None,a,b):
...   print x,y
... 
1 a
2 b
34 d
>>> c=[1,2,3,4]
>>> for (x,y) in map(None,b,c):
...   if None in (x,y): break   # required for uneven sequences,
                                # NOT containing None!
...   print x,y
... 
a 1
b 2
d 3

-- 
David Goodger    dgoodger at bigfoot.com    Open-source projects:
 - The Go Tools Project: http://gotools.sourceforge.net
 (more to come!)




More information about the Python-list mailing list