0

What's the difference between .union and | for sets in python?

>>> a = set([1, 2, 3, 4])
>>> b = set([3, 4, 5, 6])

>>> a|b
{1, 2, 3, 4, 5, 6}

>>> a.union(b)
{1, 2, 3, 4, 5, 6}
  • 2
    According to the [docs](https://docs.python.org/3/library/stdtypes.html#frozenset.union), `a|b` is the same as `a.union(b)`. – albert Jul 28 '21 at 14:58

2 Answers2

2

No difference.

In fact on the official python documentation about sets they are written together.

There is a little difference: one is an operator, so it has specific operator the operator precedence (e.g. if mixed with other set operators). On the function case, the function parenthesis explicitly fix the priority.

Giacomo Catenazzi
  • 8,519
  • 2
  • 24
  • 32
0

The original answer is not quite correct: another difference is that union will work on any iterable. From the documentation linked above:

Note, the non-operator versions of union(), intersection(), difference(), symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') & 'cbs' in favor of the more readable set('abc').intersection('cbs').

For example

>>> {1, 2}.union([1, 3])
{1, 2, 3}

vs

>>> {1 ,2} | [1, 3]
Traceback (most recent call last):
(...)
  File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'set' and 'list'