Iterating over indices in a list

Mark McEahern marklists at
Wed Feb 19 15:25:22 CET 2003

> 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?

Use Python 2.3's enumerate or make something like it:

#!/usr/bin/env python

import string

def enumerate(sequence):
    # I can't remember whether Python 2.3's enumerate returns
    # (index, item) or (item, index) and I'm too lazy to find out.
    return [(i, sequence[i]) for i in range(len(sequence))]

letters = list(string.letters)

for i, c in enumerate(letters):
    print i, c

// m

More information about the Python-list mailing list