Python for loop weird bug

Viewed 158

So in a quiz, I have given the question what the execution of this block of code gives (The one under).

a = [0, 1, 2, 3]
for a[0] in a:
    print(a[0])

I had selected error but to my surprise, it actually works and is able to print all the elements inside the list. But how?
firstly the element getting variable (usually i) is shadowing the actual variable on top of that we are getting the first element inside a number so how is it working.

1 Answers

a[0] is type of a so it can be used to iterate over the array but as in look you are assigning value in a[0] it's value will change to last element of the array.

a = [0,1,2,3]
for a[0] in a:
    print(a[0]

Will result in:

0
1
2
3

But now printing a will give you modified array:

print(a)
[3, 1, 2, 3]
Related