程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

What are the four operation methods for deleting data from the python list

編輯:Python

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 .

One 、del

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 

Two 、pop()

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']

3、 ... and 、remove()

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)

Four 、clear() : clear list

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved