環境設定 数値 文字列 正規表現 リスト タプル 集合 辞書 ループ 関数 クラス データクラス 時間 パス ファイル スクレイピング その他

Python 集合から要素を削除する(remove・discard・pop):discardは存在確認の必要なし

最終更新日 2023.02.18

Python で集合から要素を削除するには remove や discard を用います。

a = {'apple', 'lemon', 'peach'}
b = {1, 2, 3, 4}

a.remove('apple')
b.discard(2)

print(a)  # {'lemon', 'peach'}
print(b)  # {1, 3, 4}

pop でも削除できます。

a = {'apple', 'lemon', 'peach'}
b = {1, 2, 3, 4}

a.pop()
b.pop()

print(a)  # {'apple', 'lemon'}
print(b)  # {2, 3, 4}

以降はこれらのくわしい説明です。

remove

a = {'com', 'org', 'net'}

b = a.remove('com')

print(a)  # {'net', 'org'}
print(b)  # None

remove は自身を変え、なにも返しません。集合にないものを削除しようとするとエラーが起きます。

a = {'com', 'org', 'net'}

b = a.remove('me')

# KeyError: 'me'

同時に複数の要素を削除することはできません。

a = {'com', 'org', 'net'}

b = a.remove('com', 'org')

# TypeError: remove() takes exactly one argument (2 given)

引数になにも入れないとエラーが起きます。

a = {'com', 'org', 'net'}

b = a.remove()

# TypeError: remove() takes exactly one argument (0 given)

remove は削除するものが集合にあるかどうかをチェックしてから使います。

discard

a = {'com', 'org', 'net'}

b = a.discard('net')

print(a)  # {'com', 'org'}
print(b)  # None

discard は基本的に remove と同じですが、下のコードからわかるように、削除したいものがないときもエラーとなりません。

a = {'com', 'org', 'net'}

b = a.discard('me')

print(a)  # {'net', 'org', 'com'}
print(b)  # None

存在確認をする必要がないため、remove よりも discard のほうがコードは短くなるでしょう。筆者は個人的に remove を使わず、discard のみを使うようにしています。

pop

a = {'com', 'org', 'net'}

b = a.pop()

print(a)  # {'net', 'com'}
print(b)  # org

pop は Python でよく出てくる関数ですが、集合の pop は一つの要素をランダムに削除します。なにが削除されるかわからないため、特定の要素を削除するときに使われることはほとんどありません。

pop は削除したものを返します。