1. 程式人生 > >python list刪除元素的幾種方式

python list刪除元素的幾種方式

假設我們有一個列表 a=[1,2,3,4,1,2,4,5]

指定元素進行刪除

remove(x)

remove() 函式用於移除列表中 某個值的第一個匹配項,如果有多個則刪除第一個 , 注意list中不存在x,執行會報錯 無法指定位置進行刪除

>>> a=[1,2,3,4,1,2,4,5]
>>> a.remove(1)
>>> a
[2, 3, 4, 1, 2, 4, 5]
>>> a.remove(7)
Traceback (most recent call last):
  File "<stdin>",
line 1, in <module> ValueError: list.remove(x): x not in list

指定位置進行刪除

pop(index)

刪除index位置上的元素,並返回該位置上的元素值 如果index越界則會報錯

>>> a=[1,2,3,4,1,2,4,5]
>>> a.pop(-1)
5
>>> a
[1, 2, 3, 4, 1, 2, 4]
>>> a.pop(10)
Traceback (most recent call last):
  File "<stdin>"
, line 1, in <module> IndexError: pop index out of range

del x[index]

和pop所實現的功能是一樣的,但是這個沒有返回的值

>>> a=[1,2,3,4,1,2,4,5]
>>> del a[-1]
>>> a
[1, 2, 3, 4, 1, 2, 4]
>>> del a[-10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range >>>