[Tutor] How to easily recover the current index when using Python-style for loops?

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Feb 5 19:25:15 CET 2015


On 05/02/2015 18:03, boB Stepp wrote:
> On Thu, Feb 5, 2015 at 11:48 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>> On 05/02/15 17:30, 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?
>>>
>>
>> try:
>>
>>>>> help( enumerate() )
>>
>> It returns the index and item and you can specify the
>> starting index if you don't like zero.
>
> Thanks, Alan! In this instance I am happy with zero, but the link Zach
> provided says that changing the starting index wasn't implemented
> until Python 2.6.
>

We're now at 3.4 with 3.5 close to its first alpha release, so any 
particular reason that even 2.6 doesn't seem relevant to you?  No axe to 
grind, just plain old fashioned curiosity :)

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list