How can I find the union on a list of sets in Python?

PythonListPython 3.xSetSet Union

Python Problem Overview


This is the input:

x = [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}]

and the output should be:

{1, 2, 3, 4, 5}

I tried to use set().union(x) but this is the error I'm getting:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

Python Solutions


Solution 1 - Python

The signature of set.union is union(other, ...). Unpack sets from your list:

In [6]: set.union(*x)
Out[6]: {1, 2, 3, 4, 5}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRavitView Question on Stackoverflow
Solution 1 - PythonvaultahView Answer on Stackoverflow