pop(): 指定した位置の要素を削除、値を取得
pop()
メソッドは、指定したインデックスの要素を削除し、その要素の値を返します。インデックスを指定しない場合、リストの最後の要素を削除して返します。
Python
fruits = ['apple', 'grape', 'banana', 'orange']
removed_item = fruits.pop(1)
print(f"削除された要素: {removed_item}")
# 削除された要素: grape
print(f"更新後のリスト: {fruits}")
# 更新後のリスト: ['apple', 'banana', 'orange']
removed_item = fruits.pop()
print(f"削除された要素: {removed_item}")
# orange
print(f"更新後のリスト: {fruits}")
# 更新後のリスト: ['apple', 'banana']
なお、pop(0)はリストの全ての要素を操作する必要があって効率が悪いことが知られています。両端の要素を頻繁に操作するならdeque()を使います。
=> deque()
remove(): 指定した値と同じ要素を検索、最初の要素を削除
remove()はまず、指定した値をリストの要素から検索して、最初に見つかった要素を削除します。指定した値がリストにない場合は、ValueErrorが発生します。
Python
fruits = ['apple', 'banana', 'orange', 'banana']
fruits.remove('banana')
print(fruits) # ['apple', 'orange', 'banana']
del(): インデックスを指定して削除
Python
fruits = ['apple', 'banana', 'orange']
del fruits[1]
print(fruits) # ['apple', 'orange']
スライスで範囲指定を使うと、del()で複数の要素を削除できます。
Python
numbers = [0, 1, 2, 3, 4, 5, 6]
del numbers[2:5]
print(numbers) # [0, 1, 5, 6]
clear(): 全ての要素を削除
Python
fruits = ['apple', 'banana', 'cherry']
fruits.clear()
print(fruits)
# []
コメント