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

Jeff Shannon jeff at ccvcorp.com
Sat Nov 10 01:17:59 CET 2001


DeVerter at robinsonmechanical.com wrote:

> Try this.
>
> for s in my_list:
>      print my_list.index(s), ".", s
>
> This way you don't need a counter variable.

Only problem is, this fails if there are any duplicate entries in my_list.  index()
will always only find the first occurrence.

>>> breakfast = ['spam', 'eggs', 'bacon', 'spam', 'beans']
>>> for food in breakfast:
...  print breakfast.index(food), food
...
0 spam
1 eggs
2 bacon
0 spam
4 beans
>>>

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list