Eugene Yarmash
Eugene Yarmash

Reputation: 149853

How to remove multiple elements from a set?

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)?

Upvotes: 32

Views: 20599

Answers (1)

Eugene Yarmash
Eugene Yarmash

Reputation: 149853

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.

Upvotes: 61

Related Questions