1

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]
Hussain
  • 308
  • 2
  • 7
  • Imagine you did `for x in a`. Then the variable `x` would be given the value of each element of `a` in turn, right? First time round the loop, `x` is `a[0]`, second time `x` is `a[1]` and so on. Well here, `a[-1]` (the last element of `a`) is set to `a[0]` in the first iteration of the loop, `a[-1]` is set to `a[1]` in the second iteration of the loop, and so on... – slothrop Jul 28 '22 at 08:03
  • 1
    What are you trying to do and what's your expected output? – slothrop Jul 28 '22 at 08:03
  • Suggest to try this great visual platform next time for small program - https://pythontutor.com/ Learning how to debug is super important! – Daniel Hao Jul 28 '22 at 10:48
  • @slothrop I was just trying to understand how will this for loop works. – Hussain Jul 28 '22 at 13:49

1 Answers1

7

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.

KingsDev
  • 654
  • 5
  • 21
  • 1
    Nice explanation. The example can be seen more clearly using `for a[0] in …`. – S3DEV Jul 28 '22 at 08:22
  • 2
    As further context, this assignment works as lists are mutable; or more specifically, accept element assignment. This will *not* work with an immutable type such as a string or tuple. – S3DEV Jul 28 '22 at 08:32