Better way to iterate over indices?

Ethan Furman ethan at stoneleaf.us
Tue Jun 21 14:35:42 EDT 2011


Billy Mays wrote:
> I have always found that iterating over the indices of a list/tuple is 
> not very clean:
> 
> for i in range(len(myList)):
>     doStuff(i, myList[i])

Definitely not beautiful.  ;)

> I know I could use enumerate:
> 
> for i, v in enumerate(myList):
>     doStuff(i, myList[i])

If you actually need the index, then this is the way to do it.  Note 
that in most cases, you don't need the index and can iterate directly:

for v in myList:
     doStuff(v)

 From your sample code (assuming you don't need i) this does the same thing.

~Ethan~



More information about the Python-list mailing list