What is the difference between operator and method on Python set?


Python's set object represents built-in set class. Different set operations such as union, intersection, difference and symmetric difference can be performed either by calling corresponding methods or by using operators.

Union by method

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1.union(s2)
{1, 2, 3, 4, 5, 6, 7, 8}
>>> s2.union(s1)
 {1, 2, 3, 4, 5, 6, 7, 8}

Union by | operator

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1|s2
 {1, 2, 3, 4, 5, 6, 7, 8}

Intersection by method

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1.intersection(s2)
{4, 5}
>>> s2.intersection(s1)
 {4, 5}

Intersection & operator

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1&s2
{4, 5}
>>> s2&s1
 {4, 5}

Difference method

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1.difference(s2)
{1, 2, 3}
>>> s2.difference(s1)
 {8, 6, 7}

Difference - operator

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1-s2
{1, 2, 3}
>>> s2-s1
 {8, 6, 7}

Updated on: 02-Mar-2020

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements