getting an index in a for loop

Erik Max Francis max at alcyone.com
Fri Jan 31 22:40:35 EST 2003


Andrew Bennetts wrote:

> In Python 2.3 (which is still in alpha):
> 
>     >>> for index, char in enumerate('abcdefg'):
>     ...     print index, char
	...
> Otherwise in Python 2.0 or later:
> 
>     >>> s = 'abcdefg'
>     >>> for index, char in zip(range(len(s)), s):
>     ...     print index, char

Both of these are nice and tight idiomatically, but they actually have
to build the lists of tuples, and so can be prohibitive if you expect
the sequence (whether it's a string or not) to be very long indeed.  In
that case manually counting with a separate variable would be
preferable:

	index = 0
	for element in sequence:
	    # do something with index and element
	    index += 1

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ It is much safer to obey than to rule.
\__/ Thomas a Kempis
    Sade Deluxe / http://www.sadedeluxe.com/
 The ultimate Sade encyclopedia.




More information about the Python-list mailing list