0

I have a list and am iteratively performing a function on each item. I am trying to print out how far through the iteration the script is. The problem is that I can't easily get the position.

Here is what I have so far, but it generates a ValueError: 'item' is not in list.:

that_number = len(mylist)
for i in mylist: 
     this_number = mylist.index(i)
     print this_number, " out of ", that_number
     DO SOMETHING
print "Done!"

I am aiming for the output:

1 out of 3
2 out of 3
3 out of 3
Done!

This question is related in that it is trying to find the position in a list, however is there a valid way of getting the element position without using enumerate?

Community
  • 1
  • 1
  • The code you've shown shouldn't produce the error you describe, and why not use `enumerate`, anyway? – user2357112 supports Monica Feb 25 '15 at 02:00
  • 1
    There are problems of correctness and efficiency when using the ``index`` function: (i) Cannot handle duplicated elements; (ii) Quadratic complexity where it is really unnecessary. – YS-L Feb 25 '15 at 02:05

2 Answers2

1

the enumerate() function really gives you what you want. For other ways to do it though, you can do a for loop over a range:

for i in range(len(myList)):
     print myList[i], "at index", i

range(len(myList)) creates a list from 0 to len(myList) - 1 so you can use that to index into each element of the list.

Use a Generator Instead

For long lists creating another list the size of your original to loop over may be undesirable. Here is the same code as above for both python2 and 3 which will execute a for loop over a generator instead of a list.

Python 2

For Python 2, just use xrange instead of range:

for i in xrange(len(myList)):
     print myList[i], "at index", i

Python 3

For Python 3 range returns a generator, so lets just change the print statement:

for i in range(len(myList)):
     print(myList[i], "at index", i)
krock
  • 26,870
  • 12
  • 71
  • 83
  • Lots of nice little nugget extras in this clear answer: `enumerate`, `xrange`, `print`-as-function, generator understanding – dwanderson Feb 25 '15 at 02:28
0

mmm, you'll have issue with duplicates on your list. If it's only for debugging/display purposes

that_number = len(mylist)
this_number=0
for i in mylist: 
   this_number+=1
   print this_number, " out of ", that_number
   DO SOMETHING

print "Done!"

how would you deal with a list containing [1,2,3,2,1] ?

Bruce
  • 6,984
  • 1
  • 23
  • 41