Reference Counting and Garbage Collection

All objects are reference-counted. An object’s reference count is increased whenever it’s assigned to a new name or placed in a container such as a list, tuple, or dictionary, as shown here:

a = 3.4      # Creates an object '3.4' 
b = a        # Increases reference count on '3.4' 
c = [] 
c.append(b)  # Increases reference count on '3.4' 

This example creates a single object containing the value 3.4. The variable a is merely a name that refers to the newly created object. When b is assigned a, b becomes a new name for the same object, and the object’s reference count increases. Likewise, when you place b into a list, the object’s reference count increases again. In the example, only one object contains 3.4. All other ...

Get Python Essential Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.