A friend asked how to implement a delete statement in Python. In fact, there are three methods, namely: del statement, pop() method, and remove() method. The following will give you a detailed introduction.
1. del statement
If you know the position of the element to be deleted in the list, you can use the del statement. Use del to delete a list element at any position, provided its index is known.
For example:
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) del motorcycles[1] print(motorcycles)
After using the del statement to delete a value from the list, you can no longer access it.
2. Pop() method
Method pop() can delete the element at the end of the list and allow you to continue using it. The term pop comes from the analogy that a list is like a stack, and deleting the element at the end of the list is equivalent to popping the element at the top of the stack.
If you want to delete an element from the list and no longer use it in any way, use the del statement; if you want to continue to use it after deleting the element, use the pop method ().
3. remove() method
You don’t know the position of the value you want to delete from the list. If you only know the value of the element you want to remove, use the remove() method.
As an example, suppose we want to remove the value 'ducati' from the list motorcycles.
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] print(motorcycles) motorcycles.remove('ducati') print(motorcycles)
Running result:
['honda', 'yamaha', 'suzuki', 'ducati'] ['honda', 'yamaha', 'suzuki']
Note: The method remove() only deletes the first specified value. If the value to be deleted may appear multiple times in the list, you need to use a loop to determine whether all such values have been deleted.
The above is the detailed content of How to delete statements in python. For more information, please follow other related articles on the PHP Chinese website!