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

1.4k Views Asked by At

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

There are 2 best solutions below

0
Giacomo Catenazzi On

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.

0
aidangallagher4 On

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'