×

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

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.

Best Database in Python

In this tutorial, Firstly, we will understand what the term database means. Further, we will see the various databases supported in Python and when to use which one. Further, we...

7 minutes read.

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.

Python String istittle() method

Python String istittle() method The string.istittle() method returns a boolean value true if the string is a titlecased string and there is at least one character, for example uppercase characters may...

2 minutes read.

Python Kwargs Example

In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has...

5 minutes read.

Wikipedia module in Python

Wikipedia module in Python: The internet has become an essential part of all of our life which is the largest source of all the information. Therefore, it becomes very important...

7 minutes read.

Create Table Using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With this library's...

4 minutes read.

Python round() function

Python round() function The round() function in Python returns a number rounded to ‘ndigits’ precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. Syntax round(number[, ndigits]) Parameter Number: This parameter represents the...

1 minute read.

Python Control Flow Statements

This article aims to introduce you to what control flow statements are in general and Control Flow Statements in Python programming Language, the Importance of control flow statements and look...

3 minutes read.

Python ord() Function

Python ord() Function The ord() function in Python returns the number representing the Unicode code of a specified character. Syntax ord(c) Parameter c: This parameter represents a string or any character. Return This function returns the number...

1 minute read.

Python Uses

Python has advanced in recent years to rank among the programming languages that are most often used globally. It is utilized in everything, including machine learning, software testing, and website...

4 minutes read.

Python String ljust() method

Python String ljust() method The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default). Syntax String.ljust(width[, fillchar]) Parameter width: This parameter represents the...

2 minutes read.

AES CTR Python

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...

3 minutes read.

Defaultdict in Python

In this tutorial, we will study What is defaultdict in Python We will understand it with the aid of certain examples. Before this, we will have a look at dictionaries...

3 minutes read.

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

JWT Decode Python

Python's PyJWT package makes it possible to encrypt and decrypt JSON Web Tokens (JWT). JWT is a public, recognized global benchmark for safely expressing demands between two parties (RFC 7519). JSON...

7 minutes read.

Important Difference between Python 2.x and Python 3.x with Example

The comparison between Python 2 and Python 3 is given in the article that follows. Python is a computer language that can perform more tasks than other languages and is...

5 minutes read.

Class and Static Methods in Python

The method is an important concept to learn for every programmer or data analyst. We know that in OOP's concept, each object has its attributes and behaviors defined through methods....

3 minutes read.

Sklearn linear Model in Python

The most effective and reliable Python machine learning library is Sklearn. Through a Python consistency interface, it offers a variety of effective tools for statistical modeling and machine learning, including...

5 minutes read.

How to Print Pattern in Python

How to Print Pattern in Python. Pattern programs are really important for beginners and they are always asked in all the technical interviews. Multiple loops approach is used to print the different...

6 minutes read.