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 Python Basics (2015) Python Data Types Deletion

fahad lashari
fahad lashari
7,693 Points

Difference between del and .remove()? should one be preferred over the other? if so why?

Just want to know if I should be using one over the other as they both achieve the same result

2 Answers

It depends on the context.

If you only know what the element is and not it's index, you should user .remove().

If you only know the index on the other hand and not what the element is, you should use del.

Usually, you don't know both, but if you know both the index and what the element's value, I'd still use .remove(), since to me it makes more since. But, if there is a chance that there's two elements that contain the same value, you should probably use del instead (because .remove() removes the first element with the value).

I hope you understand. :)

Good luck! ~Alex

Thomas McNish
Thomas McNish
10,893 Points

It might have already been explained elsewhere, but the simple difference between del and .remove() is that del removes one specific thing in one specific place, and .remove() will just automatically remove the first instance of that thing.

For example, I can say del grocery_list[3] and it will automatically delete the 4th thing in my grocery list (remember: lists begin counting at 0). Even if the third and fourth thing on my grocery list are the same, the fourth one will get deleted, because I specified exactly where in my list I wanted something to be deleted.

If I had used grocery_list.remove('carrots'), it would automatically remove the first instance of 'carrots' from my grocery list. Even if the third and fourth items are both called 'carrots,' the third item will get deleted, because it's the first appearance of that item in my list.

If you know what your list looks like, and you know which index you want to delete, the del keyword is preferred. If you just want to remove something from your list, and you don't know where it is. Use .remove() instead. Basically, del works by specifying an item's location with an index, and .remove() works by passing in an argument (e.g. string, int, float, etc.).