Codzy

Memory and garbage collection

In Python, a variable is a label stuck on an object in memory. With b = a, you don't copy the list: you stick a second label on the same object. is checks whether two names refer to the same object (same id()), whereas == only compares values. For a real copy, use .copy() (or copy.deepcopy() for nested objects).

Python counts the references to each object. When nothing refers to an object any more (for example after del), its memory is freed automatically. The garbage collector (the gc module) also deals with cycles, when objects refer to each other.

a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(a is b, id(a) == id(b))

c = a.copy()
c.append(5)
print(a, c)
print(a == [1, 2, 3, 4], a is c)

Start the lesson