Python: setにlistやtupleを追加する

Pythonでsetとlistを使う時のtipsです。

listやtupleを引数にsetを作ることができます。

set_a = set(['a', 'b', 'c', 'a'])
# {'a', 'b', 'c'}

set_b = set(('a', 'b', 'c', 'a'))
# {'a', 'b', 'c'}

addメソッドで1要素を追加することはできますが、listやtupleを引数にすることはできません。

set_a.add('d')
# {'a', 'b', 'c', 'd'}

# 下の2つはTypeError
#set_a.add(set(['a', 'e']))
#set_a.add(['a', 'e'])

そこでsetを作って、和集合 | を取ることで追加できます。

set_a |= set(['a', 'e'])
# {'a', 'b', 'c', 'd', 'e'}

set_b |= set({'a', 'e'})
# {'a', 'b', 'c', 'e'}