getting an index in a for loop

Andrew Bennetts andrew-pythonlist at puzzling.org
Fri Jan 31 09:04:13 EST 2003


On Fri, Jan 31, 2003 at 05:43:22AM -0800, Simon Bunker wrote:
> I am iterating over a string and getting back each letter no problem.
> eg.
> 
> >>> mystring = "abcdefg"
> >>> for char in mystring:
> ...     print char
> ... 
> a
> b
> c
> d
> e
> f
> g
> 
> which is fine, but is there any way of finding out the index into the
> string we
> are referencing? Or do I have to set up a temporary counter and
> increment it in the loop each time?
> 
> I just have a feeling that Python should be cleverer than that - is
> it?

In Python 2.3 (which is still in alpha):

    >>> for index, char in enumerate('abcdefg'):
    ...     print index, char
    ... 
    0 a
    1 b
    2 c
    3 d
    4 e
    5 f
    6 g

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

-Andrew.






More information about the Python-list mailing list