Iteration over Lists and Strings

Alex Martelli aleaxit at yahoo.com
Sat Aug 28 02:58:16 EDT 2004


DeepBleu <DeepBleu at DeepBleu.org> wrote:

> I noticed the following:
> >>a = 'abba'
> >>for n in a:
> >>  print n, a.index(n)
> a 0
> b 1
> b 1
> a 0

a.index(n) returns the FIRST index x of a such thatn a[x]==n.

> (expected result:
> a 0
> b 1
> b 2
> a 3)

Misfounded expectation.  The first 'b' and the second 'b' are equal, for
example, so a.index can never possibly return different results for
them.


> What is going on?  Can someone clarify this to me?  And how can I ensure
> that the iteration produces the absolute index number **without** doing
> something like:
> >>a = 'abba'
> >>k = len(a)
> >>for m in range(0, k):
> >>  print a[m], m
> a 0
> b 1
> b 2
> a 3

That's what the enumerate built-in is for:

for m, n in enumerate(a):
    print n, m


Alex



More information about the Python-list mailing list