Iterating over indices in a list
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:
> 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:
for i in range(len(seq)):
yield i, seq[i]
for index, el in ["a", "bb", "ccc"]:
print index, el
There are other ways too.
More information about the Python-list