Can Someone please explain how For loop is Working here?

Code:

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

output:

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

How is the last element of the list coming


Solution 1:

The syntax of for <var> in <list> is used to take every element in the list, iterate over it, and, for the duration of the iteration, store it in var.

So, what your code is doing is, it's going through every element of the list list. And it is saving that in the last element of the list.

Here's a step-by-step walkthrough of what is happening:


list = [0, 1, 2, 3]

for list[-1] in list:
# First Iteration:
# list = [0, 1, 2, 3]
# First element in the list is 0.
# Store 0 in list[-1]
# list = [0, 1, 2, 0]
    print list

# Second Iteration:
# list = [0, 1, 2, 0]
# Second element in the list is 1.
# Store 1 in list[-1]
# list = [0, 1, 2, 1]
    print list

# Third Iteration:
# list = [0, 1, 2, 1]
# Third element in the list is 2.
# Store 2 in list[-1]
# list = [0, 1, 2, 2]
    print list

# Fourth Iteration:
# list = [0, 1, 2, 2]
# Fourth element in the list is 2.
# Store 2 in list[-1]
# list = [0, 1, 2, 2]
    print list

Solution 2:

It's simple, in your code, the loop is based on substitute one of the number, using the print. So, if you notice it, you will see that, the number of the loop(in your case -1), it will just substitute the last(3 in case). If you want to test it, try put:

for list[0] in list:

and it will print you:

 **output:
 [0, 1, 2, 3]
 [1, 1, 2, 3]
 [2, 1, 2, 3]
 [3, 1, 2, 3]**

Solution 3:

for loops are fancy assignment statements. You can write an equivalent while loop with an explicit assignment to model the for loop's behavior.

list = [0,1,2,3]
itr = iter(list)
while True:
    try:
        list[-1] = next(itr)
    except StopIteration:
        break

    print(list)

Each call to next returns a successive value from the list. The first three values never change, but the last value is sequentially set to the first, second, third, etc. by the assignment statement. When next finally reaches the end of the list, it returns the current value, the one set by the previous iteration, namely 2 (not 3 that was in the original list).