Issue
a = []
for i in range(10):
a.append (i*i)
for a[i] in a:
print(a[i])
For the above-mentioned code I am getting the output as follows:
0
1
4
9
16
25
36
49
64
64
I am not able to understand why 64 is getting repeated twice. If anyone knows the proper reason please explain me in detail.
Solution
With a suggestion that the loop should be like for item in a:
, let's try to know the behavior for for a[i] in a:
a = []
for i in range(10):
a.append (i*i)
print("Values before loop")
print(a, i)
for a[i] in a:
print(a[i])
print("Values after loop")
print(a, i)
Values before loop
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 9
0
1
4
9
16
25
36
49
64
64
Values after loop
[0, 1, 4, 9, 16, 25, 36, 49, 64, 64] 9
When you are iterating in above loop, i is always 9, so the iteration for a[i] in a
assigns the subsequent values from a to a[i] i.e. a[9], hence, at second final iteration, the value a[9] becomes a[8], i.e. 64
Answered By - ThePyGuy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.