Adding and Removing elements
We can add and remove elements form the set with the help of the below functions –
Example: Adding and removing elements from the Set.
Python3
# set of letters s = { 'g' , 'e' , 'k' , 's' } # adding 's' s.add( 'f' ) print ( 'Set after updating:' , s) # Discarding element from the set s.discard( 'g' ) print ( '\nSet after updating:' , s) # Removing element from the set s.remove( 'e' ) print ( '\nSet after updating:' , s) # Popping elements from the set print ( '\nPopped element' , s.pop()) print ( 'Set after updating:' , s) s.clear() print ( '\nSet after updating:' , s) |
Output
Set after updating: {'g', 'k', 's', 'e', 'f'} Set after updating: {'k', 's', 'e', 'f'} Set after updating: {'k', 's', 'f'} Popped element k Set after updating: {'s', 'f'} Set after updating: set()
Python Set Methods
A Set in Python is a collection of unique elements which are unordered and mutable. Python provides various functions to work with Set. In this article, we will see a list of all the functions provided by Python to deal with Sets.