Velocity Reviews > Better way to iterate over indices?

# Better way to iterate over indices?

Billy Mays
Guest
Posts: n/a

 06-21-2011
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])

I know I could use enumerate:

for i, v in enumerate(myList):
doStuff(i, myList[i])

....but that stiff seems clunky.

Are there any better ways to iterate over the indices of a list /tuple?

--Bill

Ian Kelly
Guest
Posts: n/a

 06-21-2011
On Tue, Jun 21, 2011 at 12:05 PM, Billy Mays <(E-Mail Removed)> wrote:
> I know I could use enumerate:
>
> for i, v in enumerate(myList):
> * *doStuff(i, myList[i])
>
> ...but that stiff seems clunky.

Why not:

for i, v in enumerate(myList):
doStuff(i, v)

Noah Hall
Guest
Posts: n/a

 06-21-2011
On Tue, Jun 21, 2011 at 7:05 PM, Billy Mays <(E-Mail Removed)> 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])

> I know I could use enumerate:
>
> for i, v in enumerate(myList):
> * *doStuff(i, myList[i])
>
> ...but that stiff seems clunky.

You're not using it properly. Think about it. You're giving two names
- i and v. You've forgotten about v -

>>> for i, v in enumerate('fish'):

.... print i, v
....
0 f
1 i
2 s
3 h

HTH.

Benjamin Kaplan
Guest
Posts: n/a

 06-21-2011
On Tue, Jun 21, 2011 at 11:05 AM, Billy Mays <(E-Mail Removed)> 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])
>
>
>
>
> I know I could use enumerate:
>
> for i, v in enumerate(myList):
> * *doStuff(i, myList[i])
>
> ...but that stiff seems clunky.

Why does enumerate seem clunky, other than the fact that you should
probably have
doStuff(i,v)
instead of myList[i] in there? It's a bit more awkward than C's
syntax, but since the typical use case is just iteration anyway, it's
not a huge deal for those few cases where you actually need the
indices.

>
> Are there any better ways to iterate over the indices of a list /tuple?
>
> --Bill
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Ethan Furman
Guest
Posts: n/a

 06-21-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~