Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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' 
like image 961
Ravit Avatar asked Jul 06 '15 18:07

Ravit


People also ask

How do you find the union of multiple sets?

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.

How do you take a union from a list in Python?

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] .

What does union () do in Python?

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.


1 Answers

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} 
like image 147
vaultah Avatar answered Oct 14 '22 15:10

vaultah