Loop over list of pairs

Richard rshaw2 at midsouth.rr.com
Fri Jun 6 19:06:32 CEST 2003


Thomas Güttler <guettler at thomas-guettler.de> wrote in message news:<bbnjsu$bb260$1 at ID-63505.news.dfncis.de>...
> Hi!
> 
> What is the prefered way of loop over
> a list like this?
>  mylist=[1, "one", 2, "two", 3, "three"]
> 
>  thomas

I would create tuple pairs inside of the list, like this:

mylist = [(1, "one"), (2, "two"), (3, "three")]

for (number, word) in mylist:
   print number, word

Since the tuples are immutable you don't have to worry as much that
the pairs could get screwed up and its very simple to iterate over.
There might be a performance hit for a long list, but for most things
would probably be fine.




More information about the Python-list mailing list