Sven
Sven

Reputation: 2889

Adding the items of a list of sets to another set

Take this example:

setA = set("A")
setB = set("B")
list = [setA, setB]

test = set("C")
test.add(list)

This gives me the expected TypeError: unhashable type: 'list'.

How do I get a set {'C', 'B', 'A'}?

Upvotes: 1

Views: 122

Answers (3)

John La Rooy
John La Rooy

Reputation: 304127

You can pass multiple arguments to test.update

test.update(*thelist)

Help on built-in function update:

update(...) Update a set with the union of itself and others.

>>> setA = set("A")
>>> setB = set("B")
>>> L = [setA, setB]
>>> test = set("C")
>>> test.update(*L)    # equivalent to calling test.update(setA, setB)
>>> test
set(['A', 'C', 'B'])

Upvotes: 1

parchment
parchment

Reputation: 4002

You need to loop over all the sets:

for s in list:
    test |= s

Upvotes: 0

Simeon Visser
Simeon Visser

Reputation: 122326

You can use set.union:

setA = set("A")
setB = set("B")
setC = set("C")
my_list = [setA, setB, setC]
result = set.union(*my_list)

You're now trying to add a list to a set which isn't possible.

If you have test = set("C") then you can do:

test |= setA | setB

This also adds the contents of setA and setB to test.

Upvotes: 2

Related Questions