Python の集合(要素の存在、追加、削除)

集合と辞書は似ています。

fruits = {'apple', 'melon', 'peach'}

print(type(fruits))  # <class 'set'>
print(len(fruits))  # 3

data = {'Alice': 27, 'Bob': 35}

print(type(data))  # <class 'dict'>
print(len(data))  # 2

コロンを使わず、要素を並べたものは集合になります。集合は順序を持たないため、下のコードは実行するたびに異なる結果を出力します。

fruits = {'apple', 'melon', 'peach'}

print(fruits)

集合の要素になりうるもの

students = {['Alice', 27], 'Bob'}

print(students)
# TypeError: unhashable type: 'list'

リスト、辞書、集合といった unhashable なものは集合の要素になりません。リストの集合、辞書の集合、集合の集合はない、ということです。

集合の要素は hashable である必要があります。整数、浮動小数点数、ブール値、文字列、そしてタプルは hashable です。

items = {-100, 3.14, True, 'Alice', ('Roll', 'Pie')}

print(items)

if ('Roll', 'Pie') in items:
	print('ロールパイ')
else:
	print('No')

要素の存在を確認する

students = {'Alice', 'Bob'}

if 'Alice' in students:
	print('Exist')
else:
	print('No')

集合に要素を追加する

items = {1, 2}

items.add(3)

print(items)
# {1, 2, 3}

items.add(2)

print(items)
# {1, 2, 3}

すでに存在する要素を追加しても、集合は変わりません。集合に集合を追加するには update を使います。

items = {1, 2}
others = {3, 4}

items.update(others)

print(items)
# {1, 2, 3, 4}

print(others)
# {3, 4}

集合から要素を削除する

items = {1, 2, 3, ('roll', 'pie')}

items.remove(1)

print(items)
# {2, 3, ('roll', 'pie')}

items.remove(('roll', 'pie'))

print(items)
# {2, 3}

存在しないものを削除するとエラーが起きます。

items = {1, 2, 3, ('roll', 'pie')}

items.remove(100)
# KeyError: 100

存在するかわからないものを削除したいときは discard を使います。

items = {1, 2, 3, ('roll', 'pie')}

items.discard(('roll', 'pie'))

print(items)
# {3, 1, 2}

items.discard(100)

print(items)
# {3, 1, 2}
Python の集合は順序のない要素の集まりです。