Harish Rudroju
Harish Rudroju

Reputation: 51

what is the significance of using list index in for loop of python?

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

Upvotes: 0

Views: 53

Answers (1)

Vikas Mulaje
Vikas Mulaje

Reputation: 765

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

Upvotes: 1

Related Questions