【Python】リストの要素削除(del, pop, remove)

この記事では、リスト(配列)の要素を削除する方法をソースコード付きで解説します。

スポンサーリンク

リストの要素を削除

Pythonでは、del文やpop, removeメソッドを用いることで要素を削除できます。

書式
1 del list[n]
2 list.pop(n)
3 list.remove(obj)

del文はリスト(list)からn+1番目の要素を削除できます。
popメソッドも同様にリスト(list)からn+1番目の要素を削除できます。
removeメソッドはリスト(list)から指定したオブジェクト(obj)を持つ要素を削除できます。(複数ある場合は、最初の要素のみ削除)

■サンプルコード
del, pop, removeメソッドを用いてリストの2番目にある要素「30」を削除するサンプルコードです。

# -*- coding: utf-8 -*-

list = [95, 30, 75, 42, 56]
del list[1]
print( list ) # [95, 75, 42, 56]

list = [95, 30, 75, 42, 56]
list.pop(1)
print( list ) # [95, 75, 42, 56]

list = [95, 30, 75, 42, 56]
list.remove(30)
print( list ) # [95, 75, 42, 56]
関連ページ
1 【Python】リストの使い方
2 【Python入門】サンプル集

コメント