mimookies
mimookies

Reputation: 63

Set in set, how to get only the elements in the set?

I have three sets:

a = set(['Apple', 'Orange', 'Pear'])
b = set(['Monkey', 'Elephant', a])
c = set([a, b])

Now, b and c obviously don't work, because sets aren't hashable. But how can I do this anyways?

What I mean by that is instead of treating the inserted set as a set, it should only get its elements and thus the sets b and c should work (like in the example).

This is just an example btw, I'm writing this code rn where sometimes sets get inserted in another set and since that doesn't work out, I'm trying to only have the elements returned. They need to be sets, because I need to use intersection and union.

set.intersection(a,b,c)
set.union(a,b,c) 

^ these should have no problem returning the values

Upvotes: 0

Views: 189

Answers (2)

H. Doebler
H. Doebler

Reputation: 651

Use this:

a = set(['Apple', 'Orange', 'Pear'])
b = set(['Monkey', 'Elephant', *a])
c = set([*a, *b])

The * unpacks the element of the expression behind it (which must be iterable).

Of course you could aswell write

b = {'Monkey', 'Elephant'} | a
c = a | b

Upvotes: 2

jfaccioni
jfaccioni

Reputation: 7539

You can used a starred expression to unpack the elements of each set in the list being passed to set:

a = set(['Apple', 'Orange', 'Pear'])
b = set(['Monkey', 'Elephant', *a])
c = set([*a, *b])

Upvotes: 2

Related Questions