Iterating over indices in a list
marklists at mceahern.com
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:
# 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
More information about the Python-list