Home  >  Article  >  Backend Development  >  What is the difference between Del and remove() on lists in Python?

What is the difference between Del and remove() on lists in Python?

王林
王林forward
2023-09-12 16:25:121477browse

What is the difference between Del and remove() on lists in Python?

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

Del keyword in Python list

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.

Example

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)

Output

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

Example

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)

Output

List =  ['Toyota', 'Benz', 'Audi', 'Bentley', 'Hyundai', 'Honda', 'Tata']
Updated List = ['Toyota', 'Benz', 'Honda', 'Tata']

Example

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

Output

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

Remove() method in Python list

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

Example

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)

Output

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

Delete and delete()

Now let us see the difference between del and remove() in Python -

in Python
deldelete()

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete