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.
Related videos on Youtube
Author by
Eugene Yarmash
By day, a software engineer. By night, also a software engineer.
Updated on March 19, 2020Comments
-
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 callings.remove(elem)
in a loop)?