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