Home > Mobile >  Why I am getting such strange behavior value for loop?
Why I am getting such strange behavior value for loop?

Time:04-03

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.

CodePudding user response:

So basically when the 1st loop finishes, the value of i is 9(because its in range 10)

Hence, When you start the 2nd loop, every iteration changes the value of a[i] ie the last element which was earlier 9.

So,

a = []
for i in range(10):
    a.append (i*i)
# Here: i = 10 and a = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    print(a[i])
# While iterating through this, the value of a[i] changes every item and is equal
# the current element of a
# When it reaches the last element, it's already a[9] so the previous value is 
# printed.

So in every Iteration:

currentElement     a[i]     a
0                  0        [0, 1, 4, 9, 16, 25, 36, 49, 64, 0]
1                  1        [0, 1, 4, 9, 16, 25, 36, 49, 64, 1]
4                  4        [0, 1, 4, 9, 16, 25, 36, 49, 64, 4]
9                  9        [0, 1, 4, 9, 16, 25, 36, 49, 64, 9]
16                 16       [0, 1, 4, 9, 16, 25, 36, 49, 64, 16]
25                 25       [0, 1, 4, 9, 16, 25, 36, 49, 64, 25]
36                 36       [0, 1, 4, 9, 16, 25, 36, 49, 64, 36]
49                 49       [0, 1, 4, 9, 16, 25, 36, 49, 64, 49]
64                 64       [0, 1, 4, 9, 16, 25, 36, 49, 64, 64]
64                 64       [0, 1, 4, 9, 16, 25, 36, 49, 64, 64]

Causing this behviour

CodePudding user response:

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

  • Related