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'
The most efficient way to join multiple sets (stored in a list of sets), use the Python one-liner set(). union(*list) that creates a new set object, calls the union() method on the new object, and unpacks all sets from the list of sets into the union() method's argument list.
To perform the union of two lists in python, we just have to create an output list that should contain elements from both the input lists. For instance, if we have list1=[1,2,3,4,5,6] and list2=[2,4,6,8,10,12] , the union of list1 and list2 will be [1,2,3,4,5,6,8,10,12] .
The union() method returns a set that contains all items from the original set, and all items from the specified set(s). You can specify as many sets you want, separated by commas. It does not have to be a set, it can be any iterable object.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With