【Python】pop

はじめに

リストの要素を削除することのできるpopメソッドについて見ていこう。

サンプルコード

pop · ki-hi-ro/python@63f6f86

sample_list = [1, 2, 3, 4, 5]

# 何も指定しない場合、最後の要素が削除される
popped_element = sample_list.pop()
print("Popped element:", popped_element)
print("List after popping the last element:", sample_list)

# インデックスを指定して要素を削除
popped_element_at_index = sample_list.pop(1)
print("Popped element at index 1:", popped_element_at_index)
print("List after popping element at index 1:", sample_list)

sample_listに対して、2通りの方法でpopメソッドを使用している。

何も指定しない場合、最後の要素が削除される。

インデックスを使用して、要素を削除することもできる。

出力結果

削除された要素と削除処理を行った後のリストを出力している。

Popped element: 5
List after popping the last element: [1, 2, 3, 4]
Popped element at index 1: 2
List after popping element at index 1: [1, 3, 4]

popメソッドの引数に何も指定しない場合、一番最後の5がポップアウトする。

Popped element: 5
List after popping the last element: [1, 2, 3, 4]

現状のsample_list : [1, 2, 3, 4]に対して、pop(1)を使用するので、以下のようになる。

Popped element at index 1: 2
List after popping element at index 1: [1, 3, 4]

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です