Search code examples
pythonlistfor-loopdata-structuresiterable

Can someone explain logic behind this python code


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


Solution

  • 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.