Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove multiple elements from a set?

Tags:

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

like image 877
Eugene Yarmash Avatar asked Mar 18 '18 13:03

Eugene Yarmash


People also ask

How do I remove multiple items from a set?

Given a set, the task is to write a Python program remove multiple elements from set. Example: Input : test_set = {6, 4, 2, 7, 9}, rem_ele = [2, 4, 8] Output : {9, 6, 7} Explanation : 2, 4 are removed from set.

How do I remove all items from a set?

clear() The clear() method removes all elements from a Set object.

How do I remove all items from a set in Python?

Python Set clear() The clear() method removes all items from the set.

How do you remove multiple elements from a list in Python?

Remove Multiple elements from list by index range using del. In this approach, we will use the del keyword to delete elements of a specified index range from the list. This function will delete all the elements from index1 to index2-1.


1 Answers

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.

like image 178
Eugene Yarmash Avatar answered Dec 29 '22 23:12

Eugene Yarmash