Home > database >  Can someone explain logic behind this python code
Can someone explain logic behind this python code

Time:08-24

This python code is giving certain output someone please explain logic behind it.

l = [1,2,3,4,5]

for l[-1] in l:

    print(l[-1])

output for this code is 1 2 3 4 4

CodePudding user response:

You iterate through the list while assigning each value to the last value of list instead of the temporary i that we always use. So you can print every value of list except the last one cause second last one overwrites it and that's why the second last is printed twice.

CodePudding user response:

Now understand for-loop behaviour in python. lets consider the following for loop:

for {val} in l: #curly braces only for the post, please do not write in python
  print(val)

What python does is launch an iterator over the list l, and for every value in the list, the variable in the {} is assigned the value and prints it -> 1 2 3 4 5

now what has happened in your code is the {} contain a reference, to the iterating list itself, specifically to -1 index of the list, aka, the last element

so the for-loop still does the exact same thing, goes over the list from left to right, but also assigns the value to the last position of the same list it is iteration over.

DRY RUN:
outside for-loop: l= [1,2,3,4,5]
iteration 1: l= [1,2,3,4,1]
iteration 2: l= [1,2,3,4,2]
iteration 3: l= [1,2,3,4,3]
iteration 4: l= [1,2,3,4,4]

now for last iteration, it is iterating over and assigning to the same position, so it outputs 4 again.

TLDR:
instead of using a temp variable in the for loop, we are using a postion in our list itself, and actually modifying it as a result every iteration.

  • Related