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

boB Stepp robertvstepp at gmail.com
Thu Feb 5 19:00:52 CET 2015


On Thu, Feb 5, 2015 at 11:45 AM, Zachary Ware
<zachary.ware+pytut at gmail.com> wrote:
> On Thu, Feb 5, 2015 at 11:30 AM, boB Stepp <robertvstepp at gmail.com> 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?
>
> Added in Python 2.3:
> https://docs.python.org/2/library/functions.html#enumerate
>
> a_list = [item1, item2, item3]
> for i, item in enumerate(a_list):
>     print 'Item number', i, 'is:', item

Thanks, Zach! I knew I had seen this feature before, but I kept
searching for the wrong terms.


-- 
boB


More information about the Tutor mailing list