1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで「リストから要素を削除する」の動作を確認してみた

Posted at

概要

Pythonで「リストから要素を削除する」の動作を確認してみました。以下のページを参考にしました。

実装

以下のファイルを作成しました。

sample.py
fruitslist = ["Orange", "Lemon", "Peach", "Grapes", "Apple"]
# "Peach" を削除
del fruitslist[2]
print(fruitslist)
# "Lemon" から "Grapes" まで削除
del fruitslist[1:3]
print(fruitslist)

numlist = ["One", "Two", "Three", "Four", "Five"]
# "Three" を削除
numlist[2:3] = []
print(numlist)
# "Two" から "Four" まで削除
numlist[1:3] = []
print(numlist)

fruitslist = ["Orange", "Lemon", "Peach", "Grapes", "Apple"]
# 最後の要素を取得して削除
print("Delete: " + fruitslist.pop())
print(fruitslist)
# 最後の要素を取得して削除
print("Delete: " + fruitslist.pop())
print(fruitslist)
# "Lemon" を取得して削除
print("Delete: " + fruitslist.pop(1))
print(fruitslist)

animallist = ["Dog", "Cat", "Monkey", "Bear", "Rabbit"]
# "Monkey"の要素を削除
animallist.remove("Monkey")
print(animallist)
# "Rabbit"の要素を削除
animallist.remove("Rabbit")
print(animallist)

colorlist = ["Blue", "Red", "Green"]
colorlist.clear()
print(colorlist)

以下のコマンドを実行しました。

$ python3 sample.py 
['Orange', 'Lemon', 'Grapes', 'Apple']
['Orange', 'Apple']
['One', 'Two', 'Four', 'Five']
['One', 'Five']
Delete: Apple
['Orange', 'Lemon', 'Peach', 'Grapes']
Delete: Grapes
['Orange', 'Lemon', 'Peach']
Delete: Lemon
['Orange', 'Peach']
['Dog', 'Cat', 'Bear', 'Rabbit']
['Dog', 'Cat', 'Bear']
[]

まとめ

何かの役に立てばと。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?