count in 'for ... in ...'

Emile van Sebille emile at fenx.com
Sat Nov 10 00:15:44 CET 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