L?? ch03 — set (集合)
テクノロジ系 / L05 collection — コレクション
L?? ch03 — set (集合)
重複を排除し、和・差・積を一発で計算する型
ゴール
setを作れる (リテラル /set()/set(list))- 重複を排除できる
- 和集合 / 積集合 / 差集合を計算できる
inで高速メンバシップ判定ができる
最小例
# main.py
a = {1, 2, 3, 2, 1}
print(a) # → {1, 2, 3} (重複が消える)
print(type(a)) # → <class 'set'>uv run python main.py
set の作り方
s1 = {1, 2, 3} # リテラル (要素が必要)
s2 = set() # 空集合は set() ({} は dict!)
s3 = set([1, 2, 2, 3]) # list から作ると重複が消える → {1, 2, 3}
s4 = set("hello") # 文字列も iterable → {'h','e','l','o'}> 注意: 空の集合を {} で作ると dict になる。空 set は必ず set()。
集合演算
a = {1, 2, 3}
b = {2, 3, 4}
a | b # 和集合 → {1, 2, 3, 4}
a & b # 積集合 → {2, 3}
a - b # 差集合 → {1}
a ^ b # 対称差 → {1, 4}メソッド版もある: a.union(b), a.intersection(b), a.difference(b), a.symmetric_difference(b)
要素の追加・削除
s = {1, 2, 3}
s.add(4) # → {1, 2, 3, 4}
s.add(2) # 既にあるので何も起きない
s.remove(3) # → {1, 2, 4} (無いと KeyError)
s.discard(99) # 無くてもエラーにならないメンバシップ判定 (高速)
users = {"alice", "bob", "carol"}
print("alice" in users) # → True
print("dave" in users) # → False- list の
inは O(n)、set のinは 平均 O(1) - 「存在チェックだけしたい」なら set が圧倒的に速い
重複排除の定番パターン
ids = [1, 2, 2, 3, 3, 3, 4] unique = list(set(ids)) # → [1, 2, 3, 4] (順序は保証されない)
> 順序を保ちたいなら dict.fromkeys(ids) を使う (Python 3.7+)。
よくある間違い
# ❌ 空集合のつもりが dict
empty = {}
print(type(empty)) # → <class 'dict'>
# ❌ set にリストは入れられない (unhashable)
s = {[1, 2]} # TypeError
# ✅ tuple は入れられる (hashable)
s = {(1, 2), (3, 4)}drill
drill/ — 2 つの list から「両方にある要素」と「どちらかにしかない要素」を求める
拡張課題
- frozenset: 不変の集合。dict のキーや別の set の要素になれる
fs = frozenset([1, 2, 3])
nested = {fs, frozenset([4, 5])} # set の中に入れられる
- 部分集合判定:
<=<>=>で集合の包含関係を見る
{1, 2} <= {1, 2, 3} # True (部分集合)
- set 内包表記: list 内包と同じ記法で set を作れる
squares = {x * x for x in range(5)} # {0, 1, 4, 9, 16}
よくある詰まり
| 症状 | 原因 | 対処 |
|---|---|---|
{} が dict になる | リテラル仕様 | 空集合は set() |
TypeError: unhashable type: 'list' | list を要素にした | tuple か frozenset に変える |
| 順序が毎回違う | set は順序を持たない | sorted(s) で安定化 |
次に学ぶ領域
| 領域 | 続けて読む |
|---|---|
| dict (キー → 値) | collection/ch04-dict |
| list との使い分け | collection/ch01-list |
| ハッシュの仕組み | Python __hash__ (発展) |
力試ししたい方は クイズ形式の演習(任意) もあります。読むだけでも十分です。