[Tutor] How to easily recover the current index when using Python-style for loops?
Alan Gauld
alan.gauld at btinternet.com
Thu Feb 5 18:48:40 CET 2015
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.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list