×

Python Set Methods

[et_pb_section][et_pb_row][et_pb_column type="4_4"][et_pb_text]

Python Set Methods

A set is a collection which is unordered and unindexed. Python has a set of built-in methods that you can use on sets.

Methods Description
add() The set.add() method adds the specified element to the set
clear() The set.add() method in Python removes all the elements from the set.
copy() This method returns a Shallow Copy for the Set
difference() The set.difference() method in Python returns a set containing the difference between two or more sets
difference_update() The difference_update() method in Python removes the common elements from the original set that are also included in another, given set.
discard() The set.discard() method in Python removes the specified  element from the Set.
intersection() The set.intersection() method in Python returns a set  that contains the intersection or the common elements between or among the given sets.
intersection_update() This method removes the elements in this set that are not present in other given set(s).
isdisjoint() The set.disjoint() method in Python checks whether the specified sets are disjoint(whether two sets have a intersection) or not.
issubset() This method returns a boolean value true is another set that contains this set.
issuperset() The set.issuperset() method in Python Returns whether this set contains another set or not
pop() The set.pop() method removes an arbitrary element from the set.
remove() The set.remove() method in python removes the specified item from the set.
symmetric_difference() This method returns a set with the symmetric differences of two sets
symmetric_difference_update() This method Updates the original Set With Symmetric Difference of the given two sets.
union() The union() method return a set containing the union of the set(s).
update() The set.update() method in Python updates the set with the union of this set and others

Example 1

# Python program explaining
# the set methods 
# initializing the set A
A = {"a", "e", "z","g"}
print("Set A: ",A)
# the set.add() method
# adding the more element in the set A
A.add("l") 
A.add("r") 
# After adding the more fruits in the set
print("After adding few more elements...")
print("New set A: ",A)
# the set.copy() method
print("Copied set B:",B)
print("Actual set A:",A)
#adding emenets in set B
B.add("g")
B.add("j")
# the set.difference() method 
# Returns a set containing the difference between Set A and SEt B
print("\nAfter subtracting Set A from Set B... ")
print("Differnce Set : ",A.difference(B))
print("Set A:",A) 
print("Set B:",B)
# the clear.set() method
# removing all the elements from Set A an Set B
A.clear()
B.clear() 
print("\nAfter clearing all the elements...")
print("Set A",A)
print("Set B",B) 

Output

Set A:  {'e', 'a', 'g', 'z'}
After adding few more elements...
New set A:  {'z', 'a', 'l', 'e', 'r', 'g'}
After the copying the dictionary... 
Copied set B: {'e', 'r', 'z', 'g', 'a', 'l'}
Actual set A: {'z', 'a', 'l', 'e', 'r', 'g'}
After subtracting Set A from Set B...  
Differnce Set :  set()
Set A: {'z', 'a', 'l', 'e', 'r', 'g'}
Set B: {'e', 'r', 'z', 'g', 'a', 'j', 'l'} 
After clearing all the elements...
Set A: set()
Set B: set() 

Example 2

# Python program explaining
# the set methods 
#initializing a set with numbers from 1 to 10
set1 = {1,2,3,4,5,6,7,8,9,10} 
print("Actual set 1:",set1)
 # initializing set2 with even numbers
set2 = {2,4,6,8,10} 
print("Actual set2: ",set2)
# the set.difference_update() method
# Removeing the items in set1 that are also included in set2
print("After subtracting set1 from set2... ") 
set1.difference_update(set2)
print("New Set 1: ",set1)
print("New Set 2:",set2) 
# the set.discard() method
# removing 3  and 5 from set1 and set2
set1.discard(3)
set2.discard(5)
# prinitg the set 
print('\nAfter discarding 3 and 5 from set1 and set2...')
print("New set1:",set1)
print("New set2:",set2)
# the set.intersection() method
# returning the common elements between set1 and set2 
print("\nIntersection between set1 and set2...")
print("set1 U set2 :",set1.intersection(set2))
# the set.union() method
# returns a new set with different items from all the sets and 
#writing the common elements between both the sets only once 
print("\nThe union of set1 and set2...")
Union= set1.union(set2)
print("A U B: ",Union) 

Output

Actual set 1: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Actual set2:  {8, 10, 2, 4, 6}
After subtracting set1 from set2... 
New Set 1:  {1, 3, 5, 7, 9} 
New Set 2: {8, 10, 2, 4, 6}
After discarding 3 and 5 from set1 and set2...
New set1: {1, 5, 7, 9} 
New set2: {8, 10, 2, 4, 6}
Intersection between set1 and set2...
set1 U set2 : set() 
The union of set1 and set2...
A U B:  {1, 2, 4, 5, 6, 7, 8, 9, 10} 

Example 3

# Python program explaining
# the set methods 
#initializing set1
set1 = {"a", "e", "i", "o","u"}
print("Set 1:",set1) 
# initializing set2
set2 = {"u", "f","a","w"} 
print("Set 2:",set2)
# the set.issuperset() method 
# will check whether set1 is a superset for set2
a= set1.issuperset(set2)
if a == True:
    { 
print("\nset1 is a superset for set2")}
elif a == False:
     {
print("\nset1 is not a superset for set2")} 
    {
print("\nset1 is a subset for set2")} 
elif a == False:
     {
print("\nset1 is not a subset for set2")} 

Output

Set 1: {'i', 'e', 'a', 'u', 'o'}
Set 2: {'a', 'w', 'u', 'f'}
set1 is not a superset for set2
set1 is not a subset for set2 
[/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section]

Related Topics

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.

Add Element to Tuple in Python

Python: Popular high-level, all-purpose programming language Python. The new version of the Python programming language, Python 3, is used for all software applications, including web development. Python is the best programming...

4 minutes read.

Python List pop() method

Python List pop() method The list.pop() method removes the item at the specified position in the list, and return it. If no index is specified, this method removes and returns the last item in the list. Syntax list.pop([i]) Parameter i:...

1 minute read.

List Comprehension in Python

Sometimes we need new lists that are completely based on previously existing lists, so to perform this operation successfully, some of the programming languages come with a syntactic construct known...

5 minutes read.

Python Line Break

Introduction In this tutorial, you will learn line breaks in python.In Python, the new line character is used to indicate the start of a new line and the end of an...

5 minutes read.

Python enumerate() function

Python enumerate() function The enumerate() function in Python takes a collection (e.g. a tuple) and returns it as an enumerate object. Syntax: enumerate(iterable, start=0) Parameter Iterable:  This parameter represents an iterable object start:    This parameter represents a number defining...

1 minute read.

Python BS4 Code

Python BS4 Code The BS4 stands for BeautifulSoup version 4.x. The BeautifulSoup is a Python library which is used for pulling out data of the HTML & XML files using the...

14 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

Unicode to String in Python

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to Import Files in Python

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Create the First GUI Application using PyQt5 in Python

GUI: A graphical user interface, or GUI, is present on most personal computers. It provides a simple experience for individuals with various computing skill levels. GUI apps may take more resources...

3 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

SKLearn Linear Module

The SK learn linear module is one such module that helps to study the relationship between the independent and dependent variables.The linear module can be implemented by using the best...

3 minutes read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

Python bytearray()

Python bytearray() Class The bytearray() class is used to return a bytearray object which is an array of the specified bytes. It gives a mutable sequence of integers in the range 0...

1 minute read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

*Args and **Kwargs in Python

Let’s know about ** (dual star / asterisk) and * (star / asterisk) are operators in Python. These stars are used in Python for parameters. Args and kwargs are special...

3 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

How to reverse a string in Python

In Python language, we have a few ways to reverse a string. In this article, let us discuss these ways and understand the suitability of these ways in different scenarios...

5 minutes read.