Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Introducing Lists Meet Lists Deletion

Akanksha Singh
Akanksha Singh
5,083 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 68,457 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,083 Points

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

Can someone explain why print(2, l) returns "[[1, 2, 3], 'b', 'c']"? I'm confused as to why it prints list "a" since it is not called in the print function.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,457 Points

Patrick Brusven, good question. When python prints an object it looks to the object itself for a representation of what to print. A variable or label itself has no printable state. So the flow is:

  • try to print list object l
  • print opening [
  • for each item in the list, try to print what its index points to.
    • try to print a or the object stilling pointed to by index 0. Since a or the index is just a label it has no printable state.
    • check what a or the index points to: a list object
    • try to print list object, recursively like printing the top list, yields opening [, then 1, 2, 3, then closing ]
  • continuing with l, print strings ’b’ and 'c’
  • print closing ]