📜  del vs remove python(1)

📅  最后修改于: 2023-12-03 15:14:39.917000             🧑  作者: Mango

del vs remove in Python

In Python, del and remove are two methods that can be used to remove elements from a list. However, the two methods have different functionalities.

del keyword

The del keyword is used to remove an element from a list based on its index. Here is an example:

fruits = ["apple", "banana", "cherry"]
del fruits[1]
print(fruits) # Output: ["apple", "cherry"]

In the above example, del fruits[1] will remove "banana" from the list.

del can also be used to delete a variable or an entire list. Here are some examples:

# del a variable
x = 5
del x

# del an entire list
fruits = ["apple", "banana", "cherry"]
del fruits
remove method

The remove method is used to remove the first occurrence of a specified element from a list. Here is an example:

fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits) # Output: ["apple", "cherry"]

In the above example, fruits.remove("banana") will remove the first occurrence of "banana" from the list.

If the element you are trying to remove does not exist in the list, remove will raise a ValueError. Here is an example:

fruits = ["apple", "banana", "cherry"]
fruits.remove("mango") # Output: ValueError: list.remove(x): x not in list
Conclusion

In summary, del is used to remove an element from a list based on its index or to delete a variable or an entire list. On the other hand, remove is used to remove the first occurrence of a specified element from a list.