Search code examples
pythoncpython

Mutable variables and memory management in Python


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?


Solution

  • 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)