0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで2つのsetを合体させる方法まとめ

Posted at

Pythonで2つのset(集合)を結合したいときには、いくつかの方法があります。
set型は重複する要素を自動的に排除してくれるため、リストと違ってユニークな値だけを扱いたい場面に適しています。

方法1:union() を使う(非破壊的)

a = {1, 2, 3}
b = {3, 4, 5}

c = a.union(b)
print(c)

出力:

{1, 2, 3, 4, 5}

ab は変更されません。


方法2:| 演算子(非破壊的)

c = a | b
print(c)

union() と同じ結果。見た目が簡潔です。


方法3:update() を使う(破壊的)

a = {1, 2, 3}
b = {3, 4, 5}

a.update(b)
print(a)

出力:

{1, 2, 3, 4, 5}

a が変更され、b の要素が追加されます。


方法4:forループ + add()(基本原理)

a = {1, 2, 3}
b = {3, 4, 5}

for item in b:
    a.add(item)

print(a)

add() は1要素ずつ追加する関数です。


比較表

方法 非破壊 / 破壊 特徴
union() 非破壊 新しいsetを返す
| 演算子 非破壊
update() 破壊 既存のsetを更新
add() + ループ 破壊 明示的な追加操作(低速)

注意点

  • add()1つの要素しか追加できないので、リストやセットなどを一括で追加したい場合は update()
  • update() に渡せるのはリスト、タプル、セットなどのイテラブル。

まとめ

  • 破壊したくない ➜ union() or |
  • 破壊してもいい ➜ update()
  • 1つずつ追加 ➜ add()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?