Iteration over Lists and Strings

DeepBleu DeepBleu at DeepBleu.org
Sat Aug 28 05:22:48 CEST 2004


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

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

The same with lists:
>>List = [1, 0 , 1]
>>for n in List:
>>  print n, List.index(n)
1 0
0 1
1 0

(expected result:
1 0
0 1
1 2)

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

Thanks -





More information about the Python-list mailing list