Python•タプルと集合
Python のタプルと集合(Set):不変性と重複なしコレクション
タプルは生成後の変更を防ぐことで整合性を保証します。集合は重複を排除し、和集合・積集合・差集合の演算をサポートします。
構文
my_tuple = (item1, item2, ...)
my_set = {item1, item2, ...}
set_union = set_a | set_b
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| tuple | Parenthesized sequence | 丸括弧で囲まれた不変の順序付きコレクション。 |
| set | Curly-brace collection | 波括弧で表される重複なし・ハッシュ可能値の順不同コレクション。 |
そのまま実行できるコード例
Compilra で実行可能Python をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
# 1. Tuples & Multiple Return / Unpacking
coordinates = (37.7749, -122.4194)
lat, lon = coordinates
print(f"Latitude: {lat}, Longitude: {lon}")
# 2. Sets: Automatic Deduplication & Set Math
roles_alice = {"Developer", "Reviewer", "Tester"}
roles_bob = {"Reviewer", "Deployer"}
# Set operations: Union, Intersection, Difference
common_roles = roles_alice & roles_bob
all_roles = roles_alice | roles_bob
alice_exclusive = roles_alice - roles_bob
print(f"\nCommon Roles (&): {common_roles}")
print(f"All Unique Roles (|): {all_roles}")
print(f"Alice Only (-): {alice_exclusive}")期待される出力:
Latitude: 37.7749, Longitude: -122.4194
Common Roles (&): {'Reviewer'}
All Unique Roles (|): {'Developer', 'Reviewer', 'Deployer', 'Tester'}
Alice Only (-): {'Developer', 'Tester'}動作のしくみ: ステップ解説
- 2-4 行目: タプルを作成し、各要素を別々の変数へアンパックします。
- 7-8 行目: 一意の文字列識別子で集合を初期化します。
- 11-13 行目: 集合の積(&)、和(|)、差(-)を計算します。
重要ポイント
- タプルは作成後に変更できません。代入を試みると TypeError が送出されます。
- 集合は挿入時に重複エントリを自動的に破棄します。
- 集合は in キーワードにより O(1) で所属判定を行えます。
よくある間違い: 末尾のカンマなしで 1 要素タプルを作成する
(42) は括弧内の整数 42 として評価されます。1 要素タプルには (42,) を使用してください。
❌ 誤り
x = (42) # type(x) is int, not tuple!
✅ 正しい例
x = (42,) # type(x) is tuple
関連するPythonチュートリアルとコンパイラ
Compilra で Python を実行・テストする
Compilraのクラウドコンパイラ上で事前設定した標準入力 (stdin) を使ってこのコードを実行できます。