1. 程式人生 > >python刪除元素&插入元素

python刪除元素&插入元素

刪除

remove 是刪除首個符合條件的元素,並不是刪除特定的索引。

a = [0, 2, 2, 3]
a.remove(2)
print(a) # [0, 2, 3],刪除指定元素

del 是根據索引(元素所在位置)來刪除的 。

del刪除整個列表。

# del[1:3]刪除指定區間
L2 = [1,2,3,4,5]
del L2[1:3]
print(L2) # [1, 4, 5],刪除1,2下標
del L2[0]
print(L2) # [4, 5],刪除0下標
del L2
print(L2) # NameError: name 'L2' is not defined

 pop返回的是彈出的那個數值,是下標定位。

b = [4, 3, 5]
print(b.pop(1)) # 3
print(b) # [4, 5]

轉:http://novell.me/master-diary/2014-06-05/difference-between-del-remove-and-pop-on.html 

插入

https://blog.csdn.net/hanshanyeyu/article/details/78839266