C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
| Python Set remove() MethodPython remove() method removes an element elem from the set. It raises error KeyError if elem is not contained in the set. See the examples given below. Signature
 remove(elem) Parameters
 elem: element to be deleted. ReturnIt returns None but throws KeyError if the value does not found in the set. Let's see some examples of remove() method to understand it's functionality. Python Set remove() Method Example 1
 Let's first see a simple example to remove an element from the set. 
# Python set remove() Method
# Creating a set
set = {1,2,3}
# Displaying elements
print(set)
# Calling method
set.remove(1)
# Displaying elements
print("After removing element: \n",set)
Output: {1, 2, 3}
After removing element: 
 {2, 3}
Python Set remove() Method Example 2It throws an error KeyError if the element is not available in the set. See the example. 
 Python set remove() Method
# Creating a set
set = {1,2,3}
# Displaying elements
print(set)
# Calling method
set.remove(22)
# Displaying elements
print("After removing element: \n",set)
Output: set.remove(22) KeyError: 22 Python Set remove() Method Example 3This method can be easily implemented into program to perform some business logic. See an examplpe below. 
# Python set remove() Method
# Creating a set
set = {'i','n','d','i','a','i','s','a','c','o','u','n','t','r','y'}
set2 = {'i','n','d','i','a','i','s','a','c','o','u','n','t','r','y'}
list = ['a','e','i','o','u']
# Displaying elements
print(set) 
for el in set:
    if el not in list:
        set2.remove(el) # Removing elements which are not in list
print(set2)
Output: {'a', 'c', 'i', 't', 'n', 'u', 'y', 's', 'd', 'o', 'r'}
{'a', 'i', 'u', 'o'}
Next TopicPython Set
 |