Python 中刪除列表元素的三種方法

列表基本上是 Python 中最常用的數據結構之一了,並且刪除操作也是經常使用的。

那到底有哪些方法可以刪除列表中的元素呢?這篇文章就來總結一下。

一共有三種方法,分別是 removepopdel,下面來詳細說明。

remove

L.remove(value) -> None -- remove first occurrence of value. Raises ValueError if the value is not present.

remove 是從列表中刪除指定的元素,參數是 value。

舉個例子:

>>> lst = [1, 2, 3]
>>> lst.remove(2)
>>> lst
[1, 3]

需要注意,remove 方法沒有返回值,而且如果刪除的元素不在列表中的話,會發生報錯。

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

pop

L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range.

pop 是刪除指定索引位置的元素,參數是 index。如果不指定索引,默認刪除列表最後一個元素。

>>> lst = [1, 2, 3]
>>> lst.pop(1)
2
>>> lst
[1, 3]
>>>
>>>
>>>
>>> lst = [1, 2, 3]
>>>
>>> lst.pop()
3

pop 方法是有返回值的,如果刪除索引超出列表範圍也會報錯。

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

del

del 一般用在字典比較多,不過也可以用在列表上。

>>> lst = [1, 2, 3]
>>> del(lst[1])
>>> lst
[1, 3]

直接傳元素值是不行的,會報錯:

>>> lst = [1, 2, 3]
>>> del(2)
  File "<stdin>", line 1
SyntaxError: cannot delete literal

del 還可以刪除整個列表:

>>> lst = [1, 2, 3]
>>> del(lst)
>>>
>>> lst
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'lst' is not defined

以上就是本文的全部內容,如果覺得還不錯的話,歡迎點贊轉發關注,感謝支持。


推薦閱讀:

  • 計算機經典書籍
  • 技術博客 硬核後端開發技術乾貨,內容包括 Python、Django、Docker、Go、Redis、ElasticSearch、Kafka、Linux 等。
  • Go 程序員 Go 學習路線圖,包括基礎專欄,進階專欄,源碼閱讀,實戰開發,面試刷題,必讀書單等一系列資源。
  • 面試題彙總 包括 Python、Go、Redis、MySQL、Kafka、數據結構、算法、編程、網絡等各種常考題。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章