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.
Adding and Removing elements
We can add and remove elements form the set with the help of the below functions –
- add(): Adds a given element to a set
- clear(): Removes all elements from the set
- discard(): Removes the element from the set
- pop(): Returns and removes a random element from the set
- remove(): Removes the element from the set
Example: Adding and removing elements from the Set.
Python3
s = { 'g' , 'e' , 'k' , 's' }
s.add( 'f' )
print ( 'Set after updating:' , s)
s.discard( 'g' )
print ( '\nSet after updating:' , s)
s.remove( 'e' )
print ( '\nSet after updating:' , s)
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()
Table of Python Set Methods
Functions Name |
Description |
add() |
Adds a given element to a set |
clear() |
Removes all elements from the set |
copy() |
Returns a shallow copy of the set |
difference() |
Returns a set that is the difference between two sets |
difference_update() |
Updates the existing caller set with the difference between two sets |
discard() |
Removes the element from the set |
frozenset() |
Return an immutable frozenset object |
intersection() |
Returns a set that has the intersection of all sets |
intersection_update() |
Updates the existing caller set with the intersection of sets |
isdisjoint() |
Checks whether the sets are disjoint or not |
issubset() |
Returns True if all elements of a set A are present in another set B |
issuperset() |
Returns True if all elements of a set A occupies set B |
pop() |
Returns and removes a random element from the set |
remove() |
Removes the element from the set |
symmetric_difference() |
Returns a set which is the symmetric difference between the two sets |
symmetric_difference_update() |
Updates the existing caller set with the symmetric difference of sets |
union() |
Returns a set that has the union of all sets |
update() |
Adds elements to the set |
Note: For more information about Python Sets, refer to Python Set Tutorial.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!