What is the difference between Del and Remove() in List in Python?

What’s the difference between Del and Remove() in Python lists?

Before exploring the difference, let’s understand what Del and Remove() are in Python lists.

The Del Keyword in Python Lists

The del keyword in Python is used to delete one or more elements from a list. We can also delete all elements, effectively deleting the entire list.

Example

Using the del keyword to delete elements from a Python list

#Create a List
myList = ["Toyota", "Benz", "Audi", "Bentley"]
print("List = ",myList)

#Delete a single element
del myList[2]

print("Updated List = n",myList)

Output

List = ['Toyota', 'Benz', 'Audi', 'Bentley']
Updated List = 
['Toyota', 'Benz', 'Bentley']

Example

Using the del keyword to delete multiple elements from a Python list

Example

Using the del keyword to delete all elements from a Python list

Remove() Method in Python Lists

The built-in remove() method in Python is used to remove elements from a List.

Example

Using the remove() method to remove elements from a Python list

#Create a List
myList = ["Toyota", "Benz", "Audi", "Bentley"]
print("List = ",myList)

#Remove a single element
myList.remove("Benz")

#Display the updated List
print("Updated List = n",myList)

Output

List = ['Toyota', 'Benz', 'Audi', 'Bentley']
Updated List =
['Toyota', 'Audi', 'Bentley']

Del vs Remove()

Now let’s look at the difference between del and remove() in Python.

del in Python remove()
del is a keyword in Python. remove() is a built-in Python method.
If the index does not exist in the Python list, an IndexError exception is raised. If the value does not exist in the Python list, a ValueError exception is raised.
del deletes an element by index. remove() deletes an element by value.
del is a simple deletion method. remove() searches the Python list for the item.

Leave a Reply

Your email address will not be published. Required fields are marked *