- 4 methods to Remove element from Python Set
- 1. Python Set Remove()
- Syntax
- Parameter
- Return Value
- How to Remove element From Python Set using Remove()
- 2. Set Discard() to Remove element from Python Set
- Syntax
- Parameters
- Return Values
- Example: Remove an element From Set using Discard()
- Code Example: Remove not exist Element
- 3. Python Set Pop()
- Syntax
- Parameter
- Return Value
- Example: How to Remove an element from Python with Pop()
- 4. Set Clear()
- Syntax
- Parameters
- Return value
- Example: Remove all elements of Set using the Clear() method
- Методы set.discard() и set.remove() в Python
- Параметры
- Возвращаемое значение
- Пример 1: Как работает?
- Пример 2
- Параметры
- Возвращаемое значение
- Пример 1: Как удалить элемента из набора в Python?
- Пример 2: Удаление несуществующего элемента
- Python Set: remove() vs discard() vs pop()
- set.remove()
- Frequently Asked:
- Removing an element from a set that does not exist
- Remove element from set if exist using remove() function
- set.discard()
- set.pop()
- Which is best: remove() vs discard() vs pop()
- Related posts:
4 methods to Remove element from Python Set
In this article, we are going to learn about 4 methods to Remove element from Python Set, all are in-built methods of Python Set to Remove elements (remove, discard, pop, clear). If you are wondering, how to delete elements from the python Set here is the answer. You can use the Built-in functions to do this job. We will cover these functions in this article, so you know, what to do to delete elements from a set.
These are the Set inbuilt function of the set to remove elements from the Set.
- Remove(): Remove an element from Set.
- Discard(): Remove an element from Set
- POP(): Remove an arbitrary(random) element
- Clear() :Remove all elemnts
1. Python Set Remove()
It removes the given element from the Set. If a passed element does not exist in Set, It raises a KeyError.
Syntax
Parameter
Return Value
- It removes the given element from the Set and updates the set. It returns None (nothing).
How to Remove element From Python Set using Remove()
In those code examples, we are removing elements from the set using the remove method. just like delete we can add single or mutiple elements to set
first_set = #removing element using remove() method first_set.remove(5) print('set after removing element :',first_set)
Traceback (most recent call last): File "main.py", line 5, in first_set.remove(10) KeyError: 10
2. Set Discard() to Remove element from Python Set
The set. discard() removes the given element from the set. If an element does not exist it will not raise an error. Instead of remove(), we can use this to avoid an error.
Syntax
Parameters
Return Values
It returns None and removes the given element from the SET and updates the Set.
Example: Remove an element From Set using Discard()
In this python program, we have removed the element 6 from the python set just passing the element 6 as a parameter to discard() method
fruit_Set = #removing element using discard() method fruit_Set.discard(6) print('set after removing element :',fruit_Set)
set after removing element :
Code Example: Remove not exist Element
In this python program example, we are removing the element that does not exist in Set using the discard() method. The Set. Discard() method does not throw any exception.
fruit_Set = #removing not exist element using discard() method print(fruit_Set.discard(8)) print('set after removing element :',fruit_Set)
None set after removing element :
3. Python Set Pop()
It removes an arbitrary(random) element from the Set and returns deleted element. It does not take any argument.
Syntax
Parameter
Return Value
It returned an arbitrary deleted element from the set and update the set. The element no longer exists in SET.
Note: If the set is empty, it raises TypeError Exception.
Example: How to Remove an element from Python with Pop()
The Pop() remove element 5,because it choose randomly.
fruit_Set = #removing element using pop() method print('deleted element : ',fruit_Set.pop()) print('set after removing element :',fruit_Set)
Note: The output might be different because Pop() deletes the arbitrary ( random) element.
deleted element : 5 set after removing element :
4. Set Clear()
The clear() in-built method of set removes all elements of the Set. It does not take any argument.
Syntax
Parameters
Return value
Example: Remove all elements of Set using the Clear() method
We are checking the value return by clear() method, as we can see it is returning None. The Set is empty after using the clear() method.
fruit_Set = #removing all elements of the set using the clear() set method print(' value return by clear method : ',fruit_Set.clear()) print('set after clear elements :',fruit_Set)
value return by clear method : None set after clear elements : set()
Методы set.discard() и set.remove() в Python
Метод discard() удаляет указанный элемент из набора (если он присутствует).
Параметры
Метод discard() в Python принимает единственный элемент x и удаляет его из набора (если он есть).
Возвращаемое значение
Метод удаляет элемент x из набора, если элемент присутствует. Возвращает None (то есть отсутствие возвращаемого значения).
Пример 1: Как работает?
numbers = numbers.discard(3) print('numbers = ', numbers) numbers.discard(10) print('numbers = ', numbers)
Пример 2
numbers = # Returns None # Meaning, absence of a return value print(numbers.discard(3)) print('numbers =', numbers)
Метод remove() удаляет указанный элемент из набора.
Параметры
Метод remove() в Python принимает один элемент в качестве аргумента и удаляет его из набора.
Возвращаемое значение
Функция удаляет указанный элемент из набора и обновляет набор. Он не возвращает никакого значения. Если элемент, переданный в remove(), не существует, генерируется исключение KeyError.
Пример 1: Как удалить элемента из набора в Python?
# language set language = # removing 'German' from language language.remove('German') # Updated language set print('Updated language set:', language)
Пример 2: Удаление несуществующего элемента
# animal set animal = # Deleting 'fish' element animal.remove('fish') # Updated animal print('Updated animal set:', animal)
Traceback (most recent call last): File "", line 5, in animal.remove('fish') KeyError: 'fish'
Python Set: remove() vs discard() vs pop()
In this article we will learn about three different functions to remove elements from a set in python i.e. remove(), discard() and pop().
set.remove()
In python, set class provides a member function remove() to delete an element from the set i.e.
It removes the given element from the set. If the element is not present in the set then it raises a KeyError.
Let’s understand more about this by some examples,
Frequently Asked:
Suppose we have a set of strings,
# set of strings set_of_str =
Now remove a string with value ‘an’ from this set using remove() function,
# Remove an element with value 'an' from the set set_of_str.remove('an') print('Modified Set Contents:') print(set_of_str)
It worked as expected and deleted the given string from the set.
Removing an element from a set that does not exist
Now suppose if we use remove() function to remove an element from a set that does not exist, then remove() function will raise KeyError i.e.
# set of strings set_of_str = # Error set_of_str.remove('here')
As string ‘here’ does not exist in the set, therefore it raised a KeyError: ‘here’.
Remove element from set if exist using remove() function
Now to avoid KeyError while calling remove() function, we need to first check if a key exist in the set or not, before trying to delete it using the remove() function i.e.
# set of strings set_of_str = value = 'here' # Check if an element exist in set, then only remove it if value in set_of_str: set_of_str.remove(value) else: print('Element does not exist in set')
Element does not exist in set
We can also avoid KeyError by using try / except, while calling remove() function,
# set of strings set_of_str = value = 'here' # Call remove() in try / except to handle KeyError try: set_of_str.remove(value) except KeyError: print('Can not delete en element, which is not present in set')
Can not delete en element, which is not present in set
set.discard()
In Python, set class also provided a function discard() to remove an element from set,
This function accepts an element as an argument and if that element exists in the set, then it deletes that. Whereas, if the given element does not exist in the set, then discard() function does nothing. So unlike remove() function it does not throw any error.
Let’s see how to remove an element from set using discard() function,
# set of strings set_of_str = # Remove an element from set set_of_str.discard('an') print('Set Contents:') print(set_of_str)
As it does not throw any error in case the given value does not exist in the set. Therefore, you should use this if you are not sure that the value to be deleted exists in the set or not. For example,
# set of strings set_of_str = # remove string that does not exist in the set set_of_str.discard('here') print('Set Contents:') print(set_of_str)
We tried to delete the string ‘here’ from the set. It was not present in the set, therefore the discard() function did nothing i.e. neither modified the set nor raised any error.
set.pop()
In python, set class provides an another member function to delete an element from set,
It removes and returns an arbitrary set element.
# set of strings set_of_str = # Remove a random element and get it in a variable delete_element = set_of_str.pop() print('Deleted Element: ',delete_element) print('Set Contents:') print(set_of_str)
Deleted Element: this Set Contents:
It deleted the element ‘end’ from the set and returned it.
Which is best: remove() vs discard() vs pop()
In a nutshell, all the three functions removes the element from a set but serves best in different scenarios,
- If you are sure that element to be deleted exists in the set then use the remove() function to delete that element. It is fast because it does not check if the given element exists in the set or not. But it will throw a KeyError in case the element does not exist in the set.
- If you are not sure that element to be deleted exists in the set or not, then use the discard() function to delete that element. It will not throw any error, if the given element does not exist in the set.
- If you want to delete a random element from a set and also want to know what is deleted. Then use the pop() function.
The complete example is as follows,
def main(): print('*** set.remove() ***') print(' ** Remove an element from set by value using set.remove() **') # set of strings set_of_str = # Remove an element with value 'an' from the set set_of_str.remove('an') print('Modified Set Contents:') print(set_of_str) print('** Trying to remove an element that is not present in the set **') # Error #set_of_str.remove('here') print('Always Remove element from set only if exist using remove() function') value = 'here' # Check if an element exist in set, then only remove it if value in set_of_str: set_of_str.remove(value) else: print('Element does not exist in set') # Call remove() in try / except to handle KeyError try: set_of_str.remove(value) except KeyError: print('Can not delete en element, which is not present in set') print('*** set.discard() ***') print('*** Remove an element from a set using set.discard() ***') # set of strings set_of_str = # Remove an element from set set_of_str.discard('an') print('Set Contents:') print(set_of_str) print('** Trying to remove an element that is not present in the set **') # set of strings set_of_str = # remove string that does not exist in the set set_of_str.discard('here') print('Set Contents:') print(set_of_str) print('*** set.pop() ***') print('*** Remove an element from a set using discard() ***') # set of strings set_of_str = # Remove a random element and get it in a variable delete_element = set_of_str.pop() print('Deleted Element: ',delete_element) print('Set Contents:') print(set_of_str) if __name__ == '__main__': main()
*** set.remove() *** ** Remove an element from set by value using set.remove() ** Modified Set Contents: ** Trying to remove an element that is not present in the set ** Always Remove element from set only if exist using remove() function Element does not exist in set Can not delete en element, which is not present in set *** set.discard() *** *** Remove an element from a set using set.discard() *** Set Contents: ** Trying to remove an element that is not present in the set ** Set Contents: *** set.pop() *** *** Remove an element from a set using discard() *** Deleted Element: is Set Contents: