Home > Net >  Python for loop intuition
Python for loop intuition

Time:07-29

I'm iterating over a list using for loop in python. I'm not able to get what is happening in this scenario.

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

output->

[0, 1, 2, 0]
[0, 1, 2, 1]
[0, 1, 2, 2]
[0, 1, 2, 2]

CodePudding user response:

In this for loop, you are setting a[-1], which is the last item in the list a, to be the currently iterated object.

The result becomes clear when walking through step by step.

a = [0, 1, 2, 3]

First iteration
Currently iterating: 0
Sets the last object in a to 0, meaning that:
a = [0, 1, 2, 0]

Second iteration
Currently iterating: 1
Sets the last object in a to 1, meaning that:
a = [0, 1, 2, 1]

Third iteration
Currently iterating: 2
Sets the last object in a to 2, meaning that:
a = [0, 1, 2, 2]

Fourth iteration
In the fourth iteration, you are just setting the last item in a to itself, meaning nothing changes. This is explains why you got the output you did.

  • Related