Difference Between Del and Remove() on Lists in Python
Lists are one of the most commonly used data types in Python. They are mutable, which means they can be changed after they are created. When working with lists, there are two ways to remove an item from the list: using the del
statement or using the remove()
method. While both methods accomplish the same goal, they do so in different ways, which can have different consequences on the rest of your code. In this article, we will explore the differences between del
and remove()
.
The del
Statement
The del
statement is a built-in Python command that deletes an object from memory. When used on a list, it can remove an item from the list by its index. Here’s an example:
fruits = ['apple', 'banana', 'cherry']
del fruits[1]
print(fruits)
This code will output:
['apple', 'cherry']
As you can see, the del
statement removed the item 'banana'
from the list.
The remove()
Method
The remove()
method is a built-in Python method that removes the first occurrence of a specified item from a list. Here’s an example:
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits)
This code will output:
['apple', 'cherry']
As you can see, the remove()
method also removed the item 'banana'
from the list.
Differences Between del
and remove()
The main difference between del
and remove()
is the way they remove items from a list. del
removes an item by its index, while remove()
removes an item by its value. This means that del
can remove any item in a list, regardless of its value, while remove()
can only remove items that match a specific value.
Another difference between del
and remove()
is that del
does not return the removed item, while remove()
does. This can be useful if you need to do something with the item before removing it from the list.
Here’s an example that demonstrates this difference:
fruits = ['apple', 'banana', 'cherry']
removed_fruit = fruits.pop(1)
print(removed_fruit)
This code will output:
'banana'
In this example, we used the pop()
method instead of remove()
or del
. pop()
removes an item from the list by its index and returns it. We stored that returned value in the variable removed_fruit
and then printed it. This allowed us to do something with the removed item before it was actually removed from the list.
Conclusion
In summary, the del
statement and the remove()
method are two ways to remove items from a list in Python. del
removes items by their index and does not return the removed item, while remove()
removes items by their value and does return the removed item. Which method you choose to use depends on what you need to do with the item you are removing and whether you need to remove it by its index or value.