[Tutor] How to easily recover the current index when using Python-style for loops?
Steven D'Aprano
steve at pearwood.info
Fri Feb 6 01:16:40 CET 2015
On Thu, Feb 05, 2015 at 11:30:38AM -0600, boB Stepp wrote:
> Python 2.4.4, Solaris 10.
>
> a_list = [item1, item2, item3]
> for item in a_list:
> print 'Item number', ???, 'is:', item
>
> Is there an easy, clever, Pythonic way (other than setting up a
> counter) to replace ??? with the current index of item in a_list?
The easy, clever, Pythonic way *is* to set up a counter.
for i, item in enumerate(a_list):
...
If you know that the list contains no duplicates, you can (but
shouldn't!) do this:
for item in a_list:
i = a_list.index(item)
but really, don't do that. Three problems: it only works with lists and
tuples, it fails when there are duplicate items, and it is slow and
inefficient. If you test with a small list, say a hundred items, you
might not notice how slow and inefficient, but then some day you'll try
it on a list with ten million items, and then you will *really* feel the
pain.
--
Steve
More information about the Tutor
mailing list