Python There are four main ways to delete data in the list , Namely del、pop()、remove()、clear(). Here's a description of this 4 There are two ways to introduce and code experience .
Delete list or delete specified data
1、 grammar
del The goal is or del( The goal is )
2、 Quick experience
2.1 Delete list
list1 = ['python', 'java', 'php']
# 2 Species writing
del list1
# del(list1 )
print(list1) # Wrong presentation NameError: name 'list1' is not defined
2.2 Delete specified data
list1 = ['python', 'java', 'php']
# del You can delete the data of the specified subscript
del list1[0]
print(list1) # ['java', 'php'] ---- 'python' Data is deleted
Delete the data of the specified subscript , If you don't specify a subscript , The last data is deleted by default , Whether by subscript or by deleting the last ,pop Functions will return the deleted data
1、 grammar :
List sequence .pop()
2、 Quick experience
# No subscript specified
list1 = ['python', 'java', 'php']
del_list = list1.pop()
print(del_list) # php
print(list1) # ['python', 'java']
# Specify subscript
list2 = ['python', 'java', 'php']
del_list2 = list2.pop(1)
print(del_list2) # java
print(list2) # ['python', 'php']
Remove the first match of a data in the list
1、 grammar
List sequence .remove( data )
2、 Quick experience
list1 = ['python', 'java', 'php']
list1.remove('python')
# list1.remove(list1[0]) # Same as above
print(list1)
1、 grammar
List sequence .clear()
2、 Quick experience
list1 = ['python', 'java', 'php']
list1.clear()
print(list1) # [] --- An empty list
The above is the simplest way to delete a list , All belong to python Introductory tutorial Category , So you can understand it by typing more code and then looking at the official documents , The operation of data is still very common in practical development .