-1

Python documentation suggests two ways to union sets:

set1 = {1, 2, 3}
set2 = {3, 4, 5}

set1 | set2       # {1, 2, 3, 4, 5}
set1.union(set2)  # {1, 2, 3, 4, 5}

I've recently come across yet another one:

set.union(set1, set2)  # {1, 2, 3, 4, 5}

How does it work?

planetp
  • 14,248
  • 20
  • 86
  • 160
  • set.union(set1,set2) is semantically equivalent to set1.union(set2). See the documentation on python objects. – B. M. Sep 20 '18 at 18:58
  • 1
    `set.union` uses the `set.union` method with `set1` being the `self` argument and `set2` being the second argument. It is essentially equivalent to `set1.union(set2)`. In python, `my_instance.some_method(arg)` is equivalent (essentially but not exactly) to `MyClass.some_method(my_instance, arg)` – juanpa.arrivillaga Sep 20 '18 at 18:58
  • Note that the arguments can be any iterable, e.g. `set().union([1,2,3], (2, 3, 4)) -> {1, 2, 3, 4}` – Alexander Sep 20 '18 at 19:00
  • You've just discovered [descriptors](https://docs.python.org/3/howto/descriptor.html#invoking-descriptors) in [method binding](https://stackoverflow.com/a/49765186/674039). – wim Sep 20 '18 at 19:01
  • 1
    Here's yet another syntax to add to your collection: `{*set1, *set2}` – wim Sep 20 '18 at 19:03

1 Answers1

0

In your example, set.union(set1, set2) actually calls the union method with set1 for the self argument. Therefore, it is equivalent to set1.union(set2).

As an aside, Python allows union-ing of arbitrary numbers of sets according to this. Actually you can see this in the Python documentation, here. Because the union method accepts *others as an argument, you can pass in any number of sets and it will perform the union of all of them.

set1 = {1, 2, 3, 4}
set2 = {1, 3, 4, 5}
set3 = {2, 4, 6, 7}

print(set.union(set1, set2, set))
# {1, 2, 3, 4, 5, 6, 7}
Woody1193
  • 7,252
  • 5
  • 40
  • 90
  • I'm not the downvoter, but the fact that union allows arbitrary number of sets is not relevant here (you would see the same behaviour if it was only accepting one other). – wim Sep 20 '18 at 19:06
  • @wim In all honesty, I thought the OP had created a third set called `set` and was calling `union` with `set` as the `self` argument, in which case this would've been valid information. On further inspection, that wasn't the case. However, his question concerns the ways `union` can be called so I think my the first part of my answer was relevant, albeit tangential – Woody1193 Sep 20 '18 at 19:08