# remove()
lst1=[10,20,30,40,10,60,70,80,90,100] lst1.remove(20) #移除对应元素 lst1.remove(10) #移除对应元素,如有相同元素移除第一个 print(lst1) lst1.remove(200) #没有该元素就报错,ValueError
E:\PycharmProjects\pythonProject\venv\Scripts\python.exe E:/PycharmProjects/pythonProject/demon1/demo4.py [30, 40, 10, 60, 70, 80, 90, 100] Traceback (most recent call last): File "E:/PycharmProjects/pythonProject/demon1/demo4.py", line 5, in <module> lst1.remove(200) #没有该元素就报错,ValueError ValueError: list.remove(x): x not in list 进程已结束,退出代码1
# pop()
lst2=[10,20,30,40,10,60,70,80,90,100,1000] lst2.pop(1) #删除一个指定索引位置上的元素 lst2.pop() #不指定索引删除最后一个元素 print(lst2)
E:\PycharmProjects\pythonProject\venv\Scripts\python.exe E:/PycharmProjects/pythonProject/demon1/demo4.py [10, 30, 40, 10, 60, 70, 80, 90, 100] 进程已结束,退出代码0
#切片------------注意: 将产生新的列表对象
lst1=[10,20,30,40,10,60,70,80,90,100,1000] lst3=[10,20,30,40,10,60,70,80,90,100,1001] lst2=lst1[1:3] #删除一个指定索引位置范围外的所有元素,产生新的列表对象 ##注意切片产生了新的列表对象lst2 print(lst2) print(lst1) ##如何不产生新的列表对象 lst3[1:3]=[] #用空列表进行替换 print(lst3)
E:\PycharmProjects\pythonProject\venv\Scripts\python.exe E:/PycharmProjects/pythonProject/demon1/demo4.py [20, 30] [10, 20, 30, 40, 10, 60, 70, 80, 90, 100, 1000] [10, 40, 10, 60, 70, 80, 90, 100, 1001]
# clear()和 del lst 清空和删除列表对象
lst1=[10,20,30,40,10,60,70,80,90,100,1000] lst1.clear()##清空列表元素 print(lst1)
E:\PycharmProjects\pythonProject\venv\Scripts\python.exe E:/PycharmProjects/pythonProject/demon1/demo4.py []
lst1=[10,20,30,40,10,60,70,80,90,100,1000] del lst1 print(lst1)
NameError: name 'lst1' is not defined
标签:10,删除,lst1,40,列表,60,70,80,6.9 From: https://www.cnblogs.com/988MQ/p/16632555.html