How to union nested Sets / A single set from nested sets?

Peter Otten __peter__ at web.de
Wed Jan 6 08:39:32 EST 2016


mviljamaa wrote:

> I'm forming sets by set.adding to sets and this leads to sets such as:
> 
> Set([ImmutableSet(['a', ImmutableSet(['a'])]), ImmutableSet(['b',
> 'c'])])
> 
> Is there way union these to a single set, i.e. get
> 
> Set(['a', 'b', 'c'])
> 
> ?

1 What version of Python are you working with?

Both Python 2.7 and 3.x have built-in set and frozenset types that you 
should use.

2 Instead of flattening the nested data I recommend that you avoid nesting 
in the first place by using update() instead of add()

>>> x = {"a", "b"}
>>> y = {"b", "c"}
>>> z = {"a", "c", "d"}
>>> result = set()
>>> for subset in x, y, z:
...     result.update(subset) #  or: result |= subset
... 
>>> result
{'b', 'a', 'd', 'c'}

For a fixed number of subsets you can avoid the loop and write

>>> result = set()
>>> result.update(x, y, z)
>>> result
{'b', 'a', 'd', 'c'}

or

>>> x | y | z
{'b', 'a', 'd', 'c'}





More information about the Python-list mailing list