Python Set Methods
Python Set Methods
The Python language provides a variety of methods for working with sets. These methods allow you to manipulate set data in different ways.
Python Set Methods
The Python set methods are as follows:
Python Set Method | Description |
add() | The add() method adds an element to a set. |
remove() | The remove() method removes an element from the set. It raises a KeyError if the element is not present in the set. |
discard() | The discard() method removes an element from the set. It does not raise an error if the element is not there in the set. |
update() | The update() method adds multiple elements to the set. |
pop() | The pop() method removes and returns an arbitrary random set element. This method raises TypeError if the set is empty. |
copy() | The copy() method returns a copy of the set. |
clear() | The clear() method removes all the elements of the set. |
union() | The union() method returns the union of two sets. |
intersection() | The intersection() method returns common elements in two sets. |
difference() | The difference() method returns the difference of two sets. |
symmetric_difference() | The symmetric_difference() method returns the symmetric difference of the two sets. |
issubset() | The issubset() method returns true if another set contains this set. |
issuperset() | The issuperset() method returns true if the set contains all the elements of another set |
isdisjoint() | The isdisjoint() method returns true if two sets have a null intersection. i.e., it returns true if two sets contain no common elements. |
Example
Example program to demo some of the set methods:
# Python Set Methods Demo Program # Python Tutorials - www.TestingDocs.com x = {1, 2, 3, 4, 5} y = {1, 2, 3} z = {6, 7, 8, 9} x.add(6) # adds element to the set print('Set x after adding an element=', x) x.remove(6) # removes element from the set print('Set x after removing an element =', x) print('Is y a subset of x ? =', y.issubset(x)) print('Is x a superset of y ?=', x.issuperset(y))
Output
Set x after adding an element= {1, 2, 3, 4, 5, 6}
Set x after removing an element = {1, 2, 3, 4, 5}
Is y a subset of x ? = True
Is x a superset of y ?= True
A sample demo program for basic set operations like Union, Intersection, Difference, and Symmetric Difference can be found here.
Python’s set methods enable easy set manipulation and comparison, making them a versatile tool for various applications.
—
Python Tutorials
Python Tutorial on this website can be found at:
https://www.testingdocs.com/python-tutorials/
More information on Python is available at the official website: