Python for loop intuition

Question:

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]
Asked By: Hussain

||

Answers:

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 explains why you got the output you did.

Answered By: KingsMMA
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.