0
Python help question
x = [1, 2, 3] y = x y[0] = 100 print(x) Output: [100, 2, 3] Why does this happen?
2 Answers
+ 5
Giovanni Paolo Balestriere ,
> what the code is doing is to create a copy from the list *x* that will be stored in a variable *y*. the result of y = x is a so called *shallow copy*.
> this does mean that variable *y* does not contain a list [1, 2, 3] like variable *x*, but just contains an *alias to the list* stored in
variable *x*. we can check this by using the builtin function id(). both variables (x and y) have the same id, so they *contain* the same object.
> if we modify an element in variable x , the result will be also visible in variable y.
> if we need to get a *complete independent copy* of the list in variable *x*, we have to make a so called *deep copy*. this requires to
import the method deepcopy from copy module. now the 2 variables have different ids.
the sample code demonstrates this behaviour:
https://code.sololearn.com/cLhrrlDaG30I/?ref=app
+ 2
List is mutable and mutable variable can be changed in place. when we change first index of y, it change the main source that is x.