Better way to iterate over indices?

B

Billy Mays

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 know I could use enumerate:

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

....but that stiff seems clunky.

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

--Bill
 
I

Ian Kelly

I know I could use enumerate:

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

...but that stiff seems clunky.


Why not:

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

Noah Hall

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 know I could use enumerate:

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

...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 -
.... print i, v
....
0 f
1 i
2 s
3 h


HTH.
 
B

Benjamin Kaplan

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 know I could use enumerate:

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

...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 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.
 
E

Ethan Furman

Billy said:
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)


Definitely not beautiful. ;)
I know I could use enumerate:

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


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~
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,173
Latest member
GeraldReund
Top