How to remove multiple elements from a set?

15,181

Yes, you can use the set.difference_update() method (or the -= operator):

>>> s = {1, 2, 3, 4, 5}
>>> s.difference_update({1, 2, 3})
>>> s
{4, 5}
>>> s -= {4, 5}
>>> s
set()

Note that the non-operator version of difference_update() will accept any iterable as an argument. In contrast, its operator-based counterpart requires its argument to be a set.

Share:
15,181

Related videos on Youtube

Eugene Yarmash
Author by

Eugene Yarmash

By day, a software engineer. By night, also a software engineer.

Updated on March 19, 2020

Comments

  • Eugene Yarmash
    Eugene Yarmash over 4 years

    Say I have a set s = {1, 2, 3, 4, 5}. Can I remove the subset {1, 2, 3} from the set in just one statement (as opposed to calling s.remove(elem) in a loop)?