Python Introducing Lists Meet Lists Deletion

Akanksha Singh
Akanksha Singh
5,081 Points

How do del and pop keyword differ in terms of garbage collection?

I know del removes the object completely and gives it for garbage collecion, and pop can be used to retrieve value from the given or last index into a variable, but when we use pop without any variable assignment to it, does it also go for garbage collection?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 56,648 Points

Good question. More precisely, del removes the label that points to an object. If the deleted label is the last reference to an object, then it is available for garbage collection. Same for pop, if it causes the last reference to an object to be removed then the object is also available for garbage collection.

Consider the following:

a = [1, 2, 3]
l = [a, 'b', 'c']
del l[0]
print(1, a)

a = [1, 2, 3]
l = [a, 'b', 'c']
del a
print(2, l)

Even though the label a was deleted, the object that was pointed to by a is still pointed to by l[0]

Akanksha Singh
Akanksha Singh
5,081 Points

Okay,so del removes the label.. Thanks a ton Chris! You are a hero :)

lenielson sousa
lenielson sousa
461 Points

Great example! Thank you!