count in 'for ... in ...'
Emile van Sebille
emile at fenx.com
Fri Nov 9 18:15:44 EST 2001
<DeVerter at robinsonmechanical.com> wrote in message
news:mailman.1005345613.25757.python-list at python.org...
>
> Try this.
>
> for s in my_list:
> print my_list.index(s), ".", s
>
> This way you don't need a counter variable.
>
While this will work for some lists, it won't for [1,2,3,2,1] or other lists
with duplicate values. Also, IIUC, consider that my_list.index(val) does
the equivalent of:
for i in range(len(my_list)):
if my_list[i] == val:
print i
break
else:
raise ValueError
In long lists this can be _very_ expensive/slow. You're really better with:
for i in range(len(my_list)):
print i, my_list[i]
At least then each entry is only visited once.
--
Emile van Sebille
emile at fenx.com
---------
More information about the Python-list
mailing list