0

I can't understand a behavior .index method inside for loop (Python 3.3.1 (v3.3.1:d9893d13c628, Apr 6 2013, 20:30:21) [MSC v.1600 64 bit (AMD64)] on win32)

L = [e for e in range(11)]
print(L)
for e in L[:]:
    print(e, L.index(e))
    L[L.index(e)] *= e
print(L)

output:

>>> 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0 0
1 1
2 2
3 3
4 2
5 5
6 6
7 7
8 8
9 3
10 10
[0, 1, 16, 81, 4, 25, 36, 49, 64, 9, 100]
>>> 

I expected the final list [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

0

1 Answer 1

3

By the time you hit 4, your list is [0, 1, 4, 9, 4, 5, 6, 7, 8, 9, 10], having replaced the first 3 elements. .index() finds the first occurence of 4, at index 2, not 5, as you appear to be expecting. The same goes for 9; you already replaced 3 with 9 earlier in the loop and L.index(9) returns 3 instead of 10.

Don't use list.index() on a changing list; use enumerate() instead:

L = [e for e in range(11)]
print(L)
for i, e in enumerate(L[:]):
    print(e, i)
    L[i] *= e
print(L)

which then results in:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

You can replace [e for e in range(11)] with a simple list(range(11)). And you can replace your whole script with:

[e * e for e in range(11)]
Sign up to request clarification or add additional context in comments.

1 Comment

Sure, accepted. This procedure also not secret for me anymore ))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.