Ceil-Ian MaralitFront End Web Development Techdegree Graduate 19,420 Points
Pop vs Del
This got me confused a bit. Does pop() and del have the same purpose?
Because Craig said that del is used to just delete the label and not the actual value. But he also said in the latter part that del is great if you want to delete the value and that he recommends pop() when we don't want the items deleted to be garbage collected.
BUT we can still access the values of the items deleted from the list when we assign it first to a variable before executing the command to delete it. Now, what's the difference between del and pop()? and when to use them?
Thanks in advance!
Chris FreemanTreehouse Moderator 58,993 Points
Good question! A simple difference is
pop() returns the item removed so it can be assigned a different label while
del simply removes the item.
If you use
pop() and do not assign a new label to the returned object it is essentially performing the same function as
The list of book title strings is actually a list of references that point to string objects stored in memory. Each string object "id" is the address in memory of the stored object.
book_list = [ "book title 1", "book title 2", "book title 3", "book title 4" ] print(book_list) #['book title 1', 'book title 2', 'book title 3', 'book title 4'] print([id(book) for book in book_list]) # [139996358750368, 139996358750256, 139996358750592, 139996358750648] saved = book_list.pop(0) print(saved) # book title 1 print(id(saved)) # 139996358750368
In a more detailed look,
pop() returns the "id" reference to the removed object so that it can be assigned to another label or used in a subsequent statement. The label
saved is assigned to the first book popped from the book list.
pop() when you want to have access to the removed item for another purpose, and use
del when you no longer want the item.
Post back if you have more questions. Good luck!!
Really good questions and answers. Thank you so much!
nikel Hayo1,942 Points
ı was confused and Chris made crystal clear. Thanks a lot for both question and answer.