Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Introducing Lists Meet Lists Deletion

Bruce McMinn
Bruce McMinn
10,029 Points

another 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

Jason Boothman
Jason Boothman
6,337 Points

I 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.

justlevy
justlevy
5,435 Points

Good 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

Steven Parker
Steven Parker
220,450 Points

The 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.