Reputation: 401
I am trying to understand how Python memory management works. If I have an mutable variable, say a list:
x = ['x1', 'x2']
print(id(x))
then I will get a certain memory address.
If I now modify x say x.append('x3')
, the memory address is the same as before because lists are mutable data types. If, however, I change x with x = x + ['x3']
and I print the address I get a different one. Why it is so? I mean, the x
variable has still the same name and all I have done is to modify its content. Why does Python change the address of the variable in this case?
Upvotes: 1
Views: 147
Reputation: 140188
when doing:
x = x + ['x3']
you're creating a new list
which is assigned to x
. The previous list held under the name x
is lost and garbage collected (unless it was stored somewhere else).
The creation of a new element, even stored under the same name, results in a new identifier.
Also note that if you want to append x3
(or another list) that is highly inefficient because of the copy of the original list to create another one. In your case, x.append('x3')
is the fastest way, and extend()
or x += ['x3','x4','x5']
is the fastest way to append to (and mutate) an existing list with multiple elements at once.
(also note that +=
mutates the list but when used on immutable types like tuple
, it still creates another tuple
)
Upvotes: 1
Reputation: 400
Variables are memory references in Python. When you say x = x + ['x3']
it merges x
and ['x3']
and build a new list. From now on, x
is pointing the new object built. That's why you get a different id. Meanwhile ['x1', 'x2']
object is deleted because nothing is pointing that object because x
is pointing the new object.
Upvotes: 0