Explain Codes LogoExplain Codes Logo

How to join two sets in one line without using "|"

python
set-union
python-sets
data-structures
Nikita BarsukovbyNikita Barsukov·Nov 19, 2024
TLDR

Combine two sets set1 and set2 together with set1.union(set2) to create a combined set.

result = {1, 2}.union({3, 4}) print(result) # Returns: {1, 2, 3, 4}

Set Unifications: Move beyond the bar

Python offers a variety of ways to join sets, in addition to the standard | operator. Let's dive into a few of these methods.

1. Union Method: the old faithful

This approach employs Python's inbuilt set.union() function. A new set is generated delivering the combined elements of your input sets.

result = set1.union(set2) print(result) # voilà, now your sets are merged, just like your favorite supergroups

2. Set Comprehension: Crafting your union

Consider using set comprehension to fetch and combine elements from multiple sets. You're limited only by your imagination - and the sets' data.

result = {x for s in [set1, set2] for x in s} print(result) # Who said set unions had to be boring?

3. Unpacking Operator: Break out of your shell

Here's a trick from Python's bag of magic. Use the unpacking operator * to collate items from each set into a new unified set.

result = {*set1, *set2} print(result) # Look ma, no "|" operator!

4. Reduce Function: Because less is more

Multiple sets to merge? Say hello to functools.reduce(). This useful function leaves no set behind, creating one to rule them all.

from functools import reduce result = reduce(set.union, [set1, set2, set3]) print(result) # Creating harmony, one set at a time

Add Complexity: Union is strength

Sometimes set unions aren't as straightforward as they appear. Let's tackle some messier, complex scenarios.

Dealing with Nested Sets

Nested sets? No problem! Flatten them first, then proceed with the usual union operation.

nested_sets = {frozenset({1, 2}), frozenset({2, 3})} result = {elem for subset in nested_sets for elem in subset} print(result) # Evicting duplicates! Property of the union state.

Enjoying the Complexities

You love a challenge and complex union cases are right up your alley. Here are some engaging ones:

Unpacking Iterables

The unpacking syntax isn't limited to sets alone, it works with any iterable. Can you say versatile?

list1 = [1, 4, 2] tuple1 = (3, 6, 5) result = {*list1, *tuple1} print(result) # Uniting iterables since Python 3.5

itertools.chain: Making connections

Use itertools.chain for non-set iterables combined with set comprehension:

from itertools import chain iter_a = [1, 3, 5] iter_b = [2, 4, 6] result = {i for i in chain(iter_a,iter_b)} print(result) # Chains and sets, together at last

Watch Out for Side Effects

While attempting to join sets in one line, beware of these gotchas:

Sneaky set.update()

The set.update() method updates the set in place, but careful, it returns None.

Performance Impact

Writing terse code could impact performance. For instance, the unpacking operator can be less efficient for large inputs.

Frozenset Immutability

Using frozenset gets you immutability. Be prepared that operations like union will return a new frozenset.