Three methods for deleting the Python list: code sharing and python
1. Use the del statement to delete an element.
>>> i1 = ["a",'b','c','d'] >>> del i1[0]>>> print(i1)['b', 'c', 'd']>>>
After the del statement deletes a value from the list, it will no longer be accessible.
2. Use pop () to delete Elements
Pop () deletes the element at the end of the list and allows you to continue using it. Appetite pop comes from the analogy that a list is a stack, and deleting the elements at the end of the list is equivalent to popping up the top elements of the stack.
>>> i1 = ['cai','rui','headsome']>>> i2 = i1.pop()>>> print(i1)['cai', 'rui']>>> print(i2)headsome>>>
Purpose: assume that the motorcycles in the list are stored based on the purchase time, you can use pop () to print a message, indicating which motorcycle was last purchased:
#!/usr/bin/env pythonmotorcycles = ['honda','yamaha','suzuki']last_owned = motorcycles.pop()print("The last motorcycle i owned was a " + last_owned.title() + '.')================================The last motorcycle i owned was a Suzuki.
The following elements are displayed at any position in the list:
#!/usr/bin/env pythonmotorcycles = ['honda','yamaha','suzuki']last_owned = motorcycles.pop(0)print("The last motorcycle i owned was a " + last_owned.title() + '.')========================================The last motorcycle i owned was a Honda.
3. remove delete an element by value
motorcycles = ['honda','yamaha','suzuki']motorcycles.remove('yamaha')print(motorcycles)====================================['honda', 'suzuki']
Note: remove () only deletes a 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 values have been deleted.
The above is all the code shared in this article about the three methods for deleting the Python list. I hope it will be helpful to you. Welcome to refer to: Python file read/write and Exception Code examples, Python network programming details, Python enumerate function code parsing, etc. If you have any questions, please point out, thank you!