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 trialAkanksha Singh
5,083 PointsHow 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
Treehouse Moderator 68,457 PointsGood 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
5,083 PointsAkanksha Singh
5,083 PointsOkay,so del removes the label.. Thanks a ton Chris! You are a hero :)
lenielson sousa
2,739 Pointslenielson sousa
2,739 PointsGreat example! Thank you!
Patrick Brusven
14,520 PointsPatrick Brusven
14,520 PointsCan 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
Treehouse Moderator 68,457 PointsChris Freeman
Treehouse Moderator 68,457 PointsPatrick 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:
l
[
a
or the object stilling pointed to by index 0. Sincea
or the index is just a label it has no printable state.a
or the index points to: alist
object[
, then 1, 2, 3, then closing]
l
, print strings’b’
and'c’
]