Tip 71 Delete Your Garbage

Pythonic Programming — by Dmitry Zinoviev (83 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Sort Big in Place | TOC | Beware of Large and Slow Ints 👉

★★★2.7, 3.4+ Python is a language with implicit memory management. The C and C++ languages require that you allocate and deallocate memory yourself. Python gently takes care of allocation and deallocation itself. When you define a variable through the assignment statement, Python creates the variable and the objects associated with it. This part is clear. But when does Python destroy variables and objects?

Each Python object has a reference count: the number of variables and other objects that refer to this object. When you create an object and do not assign it to a variable, the object has zero references:

​ ​'Hello, world!'​ ​# An object without references​

If an object is not referenced, you cannot use it. In particular, you cannot take the string from the previous example and convert it to the lowercase. But if you assign the string to a variable, you make a reference to it and use it in the future:

​ s = ​'Hello, world!'​ ​# An object with one reference​

You can create more references by assigning the same object to several variables:

​ s3 = s2 = s1 = s ​# Four references to the same object!​

When you redefine a variable, it does not point to the old object anymore, and the reference count decreases:

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.