Iterating over indices in a list

Anton Muhin antonmuhin at sendmail.ru
Wed Feb 19 15:11:59 CET 2003


Joakim Hove wrote:
> 
> 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?
> 
> 
> Regards - Joakim Hove
> 
> [*] I know I can do:
> 
>      do e in List:
>          xxxx
> 
>     but that way I don't get access to the numerical indices, which I
>     (sometimes) need for other purposes.
> 
> 

In Python 2.3 there would be built-in enumerate, but it can be easily 
implemented in Python 2.2 as well:

def enumerate(seq):
     for i in range(len(seq)):
         yield i, seq[i]

Usage:

for index, el in ["a", "bb", "ccc"]:
     print index, el

0 a
1 bb
2 ccc

There are other ways too.

HTH,
Anton.





More information about the Python-list mailing list