Before discussing the differences, let’s understand what Del and Remove() are 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, i.e. delete the entire list.
Use 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)
List = ['Toyota', 'Benz', 'Audi', 'Bentley'] Updated List = ['Toyota', 'Benz', 'Bentley']
Use the del keyword to delete multiple elements from a Python list
# Create a List myList = ["Toyota", "Benz", "Audi", "Bentley", "Hyundai", "Honda", "Tata"] print("List = ",myList) # Delete multiple element del myList[2:5] print("Updated List = \n",myList)
List = ['Toyota', 'Benz', 'Audi', 'Bentley', 'Hyundai', 'Honda', 'Tata'] Updated List = ['Toyota', 'Benz', 'Honda', 'Tata']
Use the del keyword to remove all elements from a Python list
# Create a List myList = ["Toyota", "Benz", "Audi", "Bentley"] print("List = ",myList) # Deletes the entire List del myList # The above deleted the List completely and all its elements
List = ['Toyota', 'Benz', 'Audi', 'Bentley']
The remove() built-in method in Python is used to remove elements from List.
Use the remove() method to remove elements from Python
# 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)
List = ['Toyota', 'Benz', 'Audi', 'Bentley'] Updated List = ['Toyota', 'Audi', 'Bentley']
Now let us see the difference between del and remove() in Python -
del | in Pythondelete() |
---|---|
del is a keyword in Python. | remove(0) is a built-in method in Python. |
If the index does not exist in the Python list, an indexError will be thrown. | If the value does not exist in the Python list, a valueError will be thrown. |
del works on indexes. | remove() works on values. |
del deletes the element at the specified index number. | It removes the first matching value from the Python list. |
del is simply delete. | remove() Searches the list for the item. |
The above is the detailed content of What is the difference between Del and remove() on lists in Python?. For more information, please follow other related articles on the PHP Chinese website!