getting an index in a for loop

Chad Netzer cnetzer at mail.arc.nasa.gov
Fri Jan 31 16:29:37 EST 2003


On Fri, 2003-01-31 at 06:04, Andrew Bennetts wrote:

> Otherwise in Python 2.0 or later:
>     
>     >>> s = 'abcdefg'                   
>     >>> for index, char in zip(range(len(s)), s):
>     ...     print index, char
>     ... 
>     0 a
>     1 b
>     2 c
>     3 d
>     4 e
>     5 f
>     6 g

Or the always-in-style, oldie-but-goodie method (from Python 1.x
onwards):

s = 'abcdefg'
for i in xrange( len( s ) ):
    print i, s[i]

-- 
Bay Area Python Interest Group - http://www.baypiggies.net/

Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)







More information about the Python-list mailing list