Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice assignment modifes original list

Tags:

python

There is this code:

a = [1, 2, 3, 4, 5]
a[:] = [] # and now a is also empty

Statement a[:] creates a copy of list a as I read, so if empty list [] is assigned to the copy then why original object is also modified?

like image 558
scdmb Avatar asked May 24 '26 03:05

scdmb


1 Answers

x = a[:] makes x a new list containing the same values as a

a[:] = x makes the existing list a contain the same values as x

The behaviour of an expression changes when it switches sides of the equals.

like image 114
Eric Avatar answered May 26 '26 15:05

Eric