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 trialBruce McMinn
10,030 Pointsanother del vs .pop question
What's the difference between del and .pop?
I was trying to see what it is, and maybe this is a bad example of how del and .pop are different, but the output is the same. This looks to me like I end up with the same values in each list. Maybe items in each list is the right way to say it...
OK, so let me check this as well, shapes and my_shape are both objects, their type is list, each has an id that stays constant, and their values are mutable? So is "item" something else entirely?
shapes = ["square", "circle", "polygon"]
print(shapes)
my_shape = shapes[0]
print(my_shape)
del shapes[0]
print(shapes)
print(my_shape)
del shapes
shapes = ["square", "circle", "polygon"]
print(shapes)
my_shape = shapes.pop(0)
print(my_shape)
print(shapes)
print(my_shape)
Thanks for your help.
3 Answers
justlevy
6,325 PointsGood question. This resource helped me understand.
My takeaway:
- 'pop' takes away the object using indexing and returns it
- 'del' also removes object using indexing (doesn't return it)
Hope this helps
Jason Boothman
6,349 PointsI think you are correct in that they work very similarly. The difference, as I see it, would be in what you want to do with the data removed. If you just wanted to remove it, use 'del', if you want to do something with it, use 'pop'.
Using your example...
my_shape = shapes[0]
del shapes[0]
Notice that it takes two lines of code to get the value out and and then get rid of it using 'del'.
my_shape = shapes.pop(0)
Notice how using 'pop' it only takes one line of code to get the value out and remove it.
Often times in coding there are different ways to do the same thing, so it's often about finding the most efficient method, or the method that makes the most sense to you.
Steven Parker
231,268 PointsThe difference between "del" and "pop" is the kind of argument you provide to it (the item vs. just an index), and that "pop" returns the value that is being removed.