5

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.

KidCoder
  • 164
  • 3
  • 12
  • 3
    During each loop iteration the value is assigned to a[0] and then you print a[0] - the code makes sense even so it may be a little bit unexpected. – luk2302 Jan 08 '22 at 10:41
  • 3
    In this case the for loop overwrites the first element of the list on every iteration. – Klaus D. Jan 08 '22 at 10:41
  • 6
    I would not call it a *bug* - it is an interesting *case*. Printing the whole `a` list in each iteration helps to understand what is going on. – nikeros Jan 08 '22 at 10:43
  • Your all right I just tried it. It actually overites the first element value each iteration – KidCoder Jan 08 '22 at 10:57

1 Answers1

-2

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]