any such thing as list interleaving?

"Martin v. Löwis" martin at v.loewis.de
Sat Jul 12 17:58:07 EDT 2003


Tom Plunket wrote:

> I find myself often doing the following sort of thing (sorry for
> lack of whitespace, I don't want the line to break):
> 
> for entry, index in map(lambda e,i:(e,i),aList,range(len(aList)):
>    # ...

In Python 2.3, you can write

for index, entry in enumerate(L):
   # ...

For 2.2, you can define enumerate yourself:

def enumerate(L):
   i = 0
   while 1:
     try:
       yield i, L[i]
     except IndexError:
       return
     i += 1

For older versions, yet another definition would be needed;
I leave that as an exercise.

> This also brings up a similar problem for me when iterating over
> dictionaries:
> 
> for key in myDict:
>    value = myDict[key]
>    # ...
> 
> This seems a pretty sloppy way to go about it, imo.  There must
> be something more in the Python spirit!  :)

Here, you could always write

for key, value in myDict.items():
   #...

Since 2.2, there is another method available which does not create
a list of tuples:

for key, value in myDict.iteritems():
   #...

HTH,
Martin






More information about the Python-list mailing list