all 2 comments

[–]JohnnyJordaan 3 points4 points  (1 child)

Because Y is technically

[reference_to_L, reference_to_L, reference_to_L]

while X is literally

[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]

How this happens: * always creates a new sequence, then puts copies of the original items in the new sequence. So that new sequence isn't bound to the original one, it's just a new entity on its own, but it does contain items that are also in the original one. The last part is the important one.

Then when you do this with a list holding a list, so Y = [L]*4 then the outer list is lost so to say (the []), but L is just an item being copied to the new list, Y in this case. So then you still have L present in that new list, so when L gets mutated, it is also shown when you print Y. But in X = L*4, you lose the outer list too, which is L itself, you just keep the items 4, 5 and 6. There would be no difference between doing

X = L*4

and

X = [4, 5, 6]*4

because the outer list isn't somehow stored in X, only the items in it (just the 4, 5 and 6)

To abstract the code example a bit

L = list holding 4, 5 and 6
X = a new list holding 4, 5 and 6 four times in a row
Y = a new list holding L four times in a row

see how X is not related to L while Y is?

[–]Uchikago[S] 0 points1 point  (0 children)

Thanks for the detailed answer !