Reputation: 16065
Why do set operations work with arbitrary iterables when using set methods, but not operators? To show what I mean:
>>> {0, 1, 2, 3}.intersection([0, 1])
{0, 1}
>>> {0, 1, 2, 3} & [0, 1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'set' and 'list'
>>>
>>> {0, 1, 2, 3}.union([4, 5])
{0, 1, 2, 3, 4, 5}
>>> {0, 1, 2, 3} | [4, 5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'set' and 'list'
Upvotes: 2
Views: 83
Reputation: 280291
From the docs:
Note, the non-operator versions of
union()
,intersection()
,difference()
, andsymmetric_difference()
,issubset()
, andissuperset()
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 likeset('abc') & 'cbs'
in favor of the more readableset('abc').intersection('cbs')
.
It was considered less error-prone this way.
Upvotes: 7