Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: using list slice as target of a for loop

I found this code snippet to be very interesting.

a = [0, 1, 2, 3]

for a[-1] in a:
    print(a)

Output is as follows:

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

I am trying to understand why python does that. Is it because python is trying to re-use the index? For loop somehow slices the list?

We can add or delete an element while iterating the list, but when we are trying to access the variable using index, it gives bizarre output.

Can someone help me understand the interaction between for loop and index in the list? Or simply explain this output?

like image 591
Rishi P Bhatt Avatar asked Jul 21 '18 23:07

Rishi P Bhatt


People also ask

Can you use a list in a for loop Python?

You can use a for loop to create a list of elements in three steps: Instantiate an empty list. Loop over an iterable or range of elements. Append each element to the end of the list.

Can a list be slice in Python?

In short, slicing is a flexible tool to build new lists out of an existing list. Python supports slice notation for any sequential data type like lists, strings, tuples, bytes, bytearrays, and ranges. Also, any new data structure can add its support as well.


1 Answers

It works as expected. (For some interpretation of "expected", at least.)

Re-writing your code to this, to prevent any misinterpretation of what a[-1] is at any point:

a = [a for a in range(0,4)]
for b in a:
    print (b)
    a[-1] = b
    print (a)

shows us

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

which makes it clear that the b assignment to a[-1] is done immediately, changing the list while iterating.

The four loops do the following:

  1. a[-1] gets set to the first value of the list, 0. The result is now [0,1,2,0].
  2. a[-1] gets set to the second value, 1. The result is (quite obviously) [0,1,2,1].
  3. a[-1] gets set to 2 and so the result is [0,1,2,2] – again, only a[-1] gets changed.
  4. Finally, a[-1] gets set to the last value in a, so effectively it does not change and the final result is [0,1,2,2].
like image 126
Jongware Avatar answered Sep 21 '22 11:09

Jongware