×

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

Python Dictionary update() method

Python Dictionary update() method The dictionary.update() method in Python inserts the specified items to the dictionary. Syntax dictionary.update(iterable) Parameter iterable- This parameter represents a dictionary or an iterable object with key value pairs, that will...

1 minute read.

How to upgrade PIP in python

We use the PIP command in our command prompt to install any package. PIP is used to install published Python packages in the PyPI (Python package index) or other indices....

3 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python program to find whether a given number is even or odd

Python program to find whether a given number is even or odd A number is said to be even if any number is completely divisible by 2, which means there is...

1 minute read.

Reason for Python So Popular

One of the languages that is witnessing outstanding development and acceptance every year in Python. Python has emerged as the programming language with the greatest rate of growth, and Stack...

3 minutes read.

Python Matrix Operations

Python Matrix In this section of the Python tutorial, we will look at the introduction of the matrix in Python programming. We will perform many operations on the Python matrix using...

21 minutes read.

Python Tkinter Tutorial

What is Tkinter? Tkinter is GUI library of Python. When we integrated Tinkter with Python, it provides an easy and quick way to develop GUI applications. It provides the Tk GUI...

14 minutes read.

Is Python Case-sensitive when Dealing with Identifiers

Yes, Python is a case-sensitive language while dealing with identifiers. Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. It is a case-sensitive...

6 minutes read.

Python Program for Linear Search

Introduction We employ specific algorithms to efficiently carry out our responsibilities, such as searching for an element in a given data structure. These algorithms fall under the category of searching algorithms....

4 minutes read.

How to learn python Online

Need to Learn a Programming Language 1. To get a high Paying job We know that Software Engineering is one of the top-paying professions in the world. The top criteria to be...

3 minutes read.

Python Euclidean Distance

Euclidean distance is the distance between two points with whatever of dimensions. We are using NumPy library to find and calculate the Euclidean distance. The NumPy library is used for...

1 minute read.

List Subtract in Python

The List is one of the most unique Data Structures in Python. It is generally used to store multiple values in just one single variable. It is one of the...

4 minutes read.

Python String Variable

Python programming language: 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...

4 minutes read.

Python Decorator

Python Decorator: A Decorator is an interesting feature of Python that helps the user design patterns and insert a new functionality to an existing object without making any modifications in...

6 minutes read.

File Explorer using Tkinter in Python

File Explorer: Users can control folders and files on a device using an application known as a file manager or file explorer. Customers can access, edit, copy, delete, and start moving files...

3 minutes read.

XXhash Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

6 minutes read.

Python: SetBitmap() function in wxPython

SetBitmap() function In the last tutorial, we have discussed about the GetLabelText() function of wx.MenuItem class which is one of the important function of this class. Now, in this tutorial, we...

6 minutes read.

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.

Python for Data Analysis

Data analysis uses various techniques to read, illustrate, manipulate and evaluate a particular data. You can have access to the data and keep the data updated regularly. You can append...

4 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.