0

I was trying to understand the following code

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

I expected an infinite loop printing 3 but the output is quite incomprehensible as below

output:

0
1
2
2

can somebody Please explain the working of this code!

Thanks in advance

Harish Rudroju
  • 43
  • 2
  • 10
  • Mentally insert the line `a[-1] = i` inside that loop, where `i` is the current value in the iteration. `for a[-1] ...` assigns the iteration value to `a[-1]` on every iteration… – deceze Apr 24 '20 at 07:20
  • 1
    This is an interesting mental exercise. But I fail to see why anyone would write code like this. – Rajarishi Devarajan Apr 24 '20 at 07:37

1 Answers1

1

in keyword in for loop is different than other use cases.

in this for loop list returns an iterator and assign it to the variable in your case last element of list

to break your code this is what it is doing in background

for i in a:
    a[-1] = i
    print(a[-1])

reference: https://docs.python.org/3/reference/compound_stmts.html#the-for-statement

and Python 'in' keyword in expression vs. in for loop

Vikas Mulaje
  • 727
  • 6
  • 11