Iterating over indices in a list

Gerrit Holl gerrit at nl.linux.org
Wed Feb 19 15:22:30 CET 2003


Joakim Hove schreef op woensdag 19 februari om 15:08:57 +0000:
> 
> 
> Hello all, 
> 
> I find my code quite often containing statements like this[*]:
> 
>   do index in (range(len(List))):
>       if List[index]....
> 
> 
> Somewhere I stumbled over a new, and more elegant (based on iterators
> ?) alternative to this ugly construction, but now I can not find
> it. Any suggestions?

As of Python 2.3, you can do:

 12 >>> for index, item in enumerate(string.lowercase):
 12 ...  print item, "is letter number", index, "in the alphabet!"

See also:

    * http://www.python.org/doc/2.3a1/whatsnew/section-enumerate.html
    * http://www.python.org/peps/pep-0279.html
    * http://www.python.org/dev/doc/devel/lib/built-in-funcs.html#l2h-18

yours,
Gerrit.

-- 
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/





More information about the Python-list mailing list