Python のリストにおける del、remove、pop の違い 質問する

Python のリストにおける del、remove、pop の違い 質問する

Python でリストから要素を削除するこれら 3 つの方法には違いがありますか?

a = [1, 2, 3]
a.remove(2)
a               # [1, 3]

a = [1, 2, 3]
del a[1]
a               # [1, 3]

a = [1, 2, 3]
a.pop(1)        # 2
a               # [1, 3]

ベストアンサー1

リストから要素を削除する 3 つの異なる方法の効果:

remove特定のインデックスではなく、最初に一致するを削除します。

>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]

del特定のインデックスのアイテムを削除します。

>>> a = [9, 8, 7, 6]
>>> del a[1]
>>> a
[9, 7, 6]

pop特定のインデックスにある項目を削除して返します

>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]

エラーモードも異なります。

>>> a = [4, 5, 6]
>>> a.remove(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> del a[7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> a.pop(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range

おすすめ記事