Open In App

Python Set Methods

Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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()

 
 

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.

 



Last Updated : 12 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Similar Reads