The assignment operator in Python is not allocation, it is just setting a reference to an object.
This seems to indicate that x and y are now 2 separate lists?
Yes, that is
[1, 2, 3]
creates an object, a list, that contains the objects 1, 2, 3. Similarily,
[555, 666]
creates another list that contains the objects 555, 666. The assignment operation
x = y
merely says point x to the same object as y. There is no copying involved.
I feel like I'm missing something really obvious here
The thing to keep in mind is that Python's assignment operator (=) is setting the left-hand variable to be a reference to an object, while the allocation of the object is an explicit operation in itself. Assigning one variable to the value of an other means setting both variables to point to the same object.
But their object ID's match to indicate that they're the same memory address.
id()
returns the id of the object the variable points to, not the id of the variable.
You can never change the value of an object by assigning it to a variable - if you want to change the content of the list pointed to by y
, say, you have to use the subscription operator [i]
where i
is the 0-based index, e.g.
y[2] = 5
=> [1, 2, 5]
or for that matter any value-changing operation supported by the list object, e.g. del
, append
or extend
.
some other method if you wanted x and y to be independent [asked in comments]
Here's a few ways
x = [1, 2, 3]; y = [555, 666]
- as in your example
x = [1, 2, 3]; y = list(x)
- both point to a different list object yet with the same content
import copy; x = [[1], [2], [3]]; y = copy.deepcopy(x)
- different list objects with different contents
Note that deepcopy
makes a copy of every (mutable) object contained in the list, while immutable objects are not copied but referenced to the same objects (i.e. the objects 1, 2, 3 are still the same id()
even after deepcopy
because numbers are immutable).