SlideShare a Scribd company logo
SET
SET
• A set is an unordered collection of items. Every element is unique (no
duplicates) and must be immutable (which cannot be changed).
• However, the set itself is mutable. We can add or remove items from it.
• Sets can be used to perform mathematical set operations like union,
intersection, symmetric difference etc.
Creating SET
• A set is a collection which is unordered and unindexed.
• A set iss created by placing all the items(elements) inside with curly
brackets{},separated by comma or by using the built-in function set().
• It can have any number of items and they may be of different types (integer, float, tuple,
string etc.).
• Empty curly braces {} will make an empty dictionary in Python.
• To make a set without any elements we use the set() function without any argument.
Creating SET
• Important : But a set cannot have a mutable element, like list, set or dictionary, as its
element.
Example :
set_four={1,2,[3,4]}
print set_four
#output : set_four={1,2,[3,4]}
TypeError: unhashable type: 'list’Because Set is immutable
and list is mutable so we can’t contain list in set.
Creating SET
• We can make set from a list.
my_set = set([1,2,3,2])
print(my_set)
#Output :
{1, 2, 3}
Access Items
• You cannot access items in a set by referring to an index, since sets are unordered the
items has no index.
• But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword.
thisset = {“sad", “happy", “love“,”hate”}
for x in thisset:
print(x)
# Output :
sad
happy
love
hate
Change SET methods
• To add one item to a set use the add( ) method.
• To add more than one item to a set use the update() method.
• The update() method can take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are avoided.
Remove element from SET
• A particular item can be removed from set using methods, discard() and remove().
• The only difference between the two is that, while using discard() if the item does not
exist in the set, it remains unchanged. But remove() will raise an error in such condition.
• You can also use the pop(), method to remove an item, but this method will remove the
last item. Remember that sets are unordered, so you will not know what item that gets
removed. The return value of the pop() method is the removed item.
• The clear() method empties the set.
• The del keyword will delete the set completely.
Mathematical Set Operations
Union( )
• Union operation is performed using | operator. Same can be accomplished using the
method union(). Union of sets is a set of all elements from both A & B sets.
# set operations
A = {1, 3, 5, 7, 9}
B = {2, 4, 6,8,10}
print(A|B)
print(A.union(B))
print(B.union(A))
#Above all print statement output will be same.
#Output :{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Intersection( )
• Intersection operation is performed using & operator. Same can be accomplished using
the method intersection(). Intersection of sets is a set of elements that are common in
both sets.
# set operations
A = {1, 3, 4, 7, 8}
B = {2, 4, 3,8,10}
print(A&B)
print(A.intersection(B))
print(B.intersection(A))
#Above all print statement output will be same.
#Output :{3,4,8}
Difference( )
• Difference is performed using - operator. Same can be accomplished using the method
difference(). Difference of A and B (A - B) is a set of elements that are only in A but not
in B. Similarly, B - A is a set of element in B but not in A.
# set operations
A = {1, 3, 4, 7, 8}
B = {2, 4, 3,8,10}
print(A-B)
print(A. difference(B))
#output :{1, 7}
print(B-A)
print(B.difference(A))
#output :{2,10}
symmetric_difference( )
• Symmetric Difference of A and B is a set of elements in both A and B except those that
are common in both. Symmetric difference is performed using ^ operator. Same can be
accomplished using the method symmetric_difference().
# set operations
A = {1, 3, 4, 7, 8}
B = {2, 4, 3,8,10}
print(A^B)
print(A. symmetric_difference(B))
print(B^A)
print(B. symmetric_difference (A))
#Above all print statement output will be same.
#output :{1,2,7,10}
Copy( )
• The copy() method copies the set.
fruits = {"apple", "banana", "cherry"}
x = fruits.copy()
print(x)
difference_update( )
• The difference_update() method removes the items that exist in both sets.
• The difference_update() method is different from the difference() method, because the
difference() method returns a new set, without the unwanted items, and the
difference_update() method removes the unwanted items from the original set.
• Syntax :
• A.difference_update(B)
• Here, A and B are two sets. The difference_update() updates set A with the set
difference of A-B.
• The difference_update() returns None indicating the object (set) is mutated.
difference_update( )
• Example:
A = {'a', 'c', 'g', 'd'}
B = {'c', 'f', 'g'}
result = A.difference_update(B)
print('A = ', A)
print('B = ', B)
print('result = ', result)
#output: ( 'A = ', set(['a', 'd']))
('B = ', set(['c', 'g', 'f']))
('result = ', None)
A = {'a', 'c', 'g', 'd'}
B = {'c', 'f', 'g'}
result = B.difference_update(A)
print('A = ', A)
print('B = ', B)
print('result = ', result)
#output: ('A = ', set(['a', 'c', 'd', 'g']))
('B = ', set(['f']))
('result = ', None)
symmentric_difference_update( )
• The symmetric_difference_update() method finds the symmetric
difference of two sets and updates the set calling it.
• Syntax :
• A.symmetric_difference_update(B)
• The symmetric_difference_update() returns None (returns nothing).
Rather, it updates the set calling it.
symmentric_difference_update( )
Example:
A = {'a', 'c', 'd'}
B = {'c', 'd', 'e’ }
result=A.symmetric_difference_update(B)
print('A =', A)
print('B =', B)
print('result =', result)
Output :
A = {'a', 'e'}
B = {'d', 'c', 'e'}
result = None
intersection_update( )
• The intersection of two or more sets is the set of elements which are
common to all sets.
• Syntax:
• A.intersection_update(*other_sets)
• The intersection_update() allows arbitrary number of arguments (sets).
• This method returns None (meaning, absence of a return value). It only
updates the set calling the intersection_update() method.
This method returns None (meaning, absence of a return value). It only updates the set calling the intersection_update() method.
intersection_update( )
Example :
A = {1, 2, 3, 4}
B = {2, 3, 4, 5, 6}
C = {4, 5, 6, 9, 10}
result = C.intersection_update(B, A)
print('result =', result)
print('C =', C)
print('B =', B)
print('A =', A)
#Output :
result = None
C = {4}
B = {2, 3, 4, 5, 6}
A = {1, 2, 3, 4}
issubset( )
• The issubset( ) method returns True if all elements of a set are present in another
set (passed as an argument). If not, it returns False.
• Set A is said to be the subset of set B if all elements of A are in B.
• Syntax:
• A.issubset(B)
• The issubset() returns
✓True if A is a subset of B
✓False if A is not a subset of B
issuperset( )
• The issuperset() method returns True if all items in the specified set exists in the original set,
otherwise it retuns False.
• Syntax:
• A.issuperset(B)
• The issuperset() returns
✓ True if A is a superset of B
# Return True if all items in set B are present in set A.
✓ False if A is not a superset of B
# Return False if not all items in set B are present in set A.
issubset( )
• Example :
A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
C = {1, 2, 4, 5}
print(A.issubset(B))
print(B.issubset(A))
print(A.issubset(C))
print(C.issubset(B))
Output:
True
False
False
True
disjoint( )
• The isdisjoint() method returns True if two sets are disjoint sets. If not, it returns False.
• Two sets are said to be disjoint sets if they have no common elements.
• Syntax:
• A.disjoint( )
• The isdisjoint() method returns
✓ True if two sets are disjoint sets
✓ (if set_a and set_b are disjoint sets in above syntax)
✓ False if two sets are not disjoint sets
len( ),set( )
• To determine how many items a set has, use the len() method.
• Syntax: len(set_name)
• It is also possible to use the set() constructor to make a set.
• Example:
thisset = set(("apple", "banana", "cherry"))
# note the double round-brackets
print(thisset)

More Related Content

What's hot

Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Linked list
Linked listLinked list
Linked list
KalaivaniKS1
 
Html forms
Html formsHtml forms
Html forms
Himanshu Pathak
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
nitamhaske
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
•sreejith •sree
 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
Lakshman Basnet
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
Mohammed Sikander
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
VedaGayathri1
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
DPS Ranipur Haridwar UK
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
Sujith Kumar
 
Java Collections
Java  Collections Java  Collections
Php array
Php arrayPhp array
Php array
Nikul Shah
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
Ñirmal Tatiwal
 

What's hot (20)

Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Linked list
Linked listLinked list
Linked list
 
Html forms
Html formsHtml forms
Html forms
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Php array
Php arrayPhp array
Php array
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 

Similar to Set methods in python

Set data structure
Set data structure Set data structure
Set data structure Tech_MX
 
Question In C Programming In mathematics, a set is a colle...Sav.pdf
Question In C Programming In mathematics, a set is a colle...Sav.pdfQuestion In C Programming In mathematics, a set is a colle...Sav.pdf
Question In C Programming In mathematics, a set is a colle...Sav.pdf
arihantcomp1008
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
maamir farooq
 
Blackbox task 2
Blackbox task 2Blackbox task 2
Blackbox task 2
blackbox90s
 
Python_Sets(1).pptx
Python_Sets(1).pptxPython_Sets(1).pptx
Python_Sets(1).pptx
rishiabes
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
Abhishek Tirkey
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
GauravPandey43518
 
Set relationship, set operation and sigmoid
Set relationship, set operation and sigmoidSet relationship, set operation and sigmoid
Set relationship, set operation and sigmoid
Kanza batool
 
Java
JavaJava
sets and maps
 sets and maps sets and maps
sets and maps
Rajkattamuri
 
Python Sets_Dictionary.pptx
Python Sets_Dictionary.pptxPython Sets_Dictionary.pptx
Python Sets_Dictionary.pptx
M Vishnuvardhan Reddy
 
07012023.pptx
07012023.pptx07012023.pptx
07012023.pptx
NareshBopparathi1
 
package lab7 public class SetOperations public static.pdf
package lab7     public class SetOperations  public static.pdfpackage lab7     public class SetOperations  public static.pdf
package lab7 public class SetOperations public static.pdf
syedabdul78662
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
mdfkhan625
 
Discrete mathematic
Discrete mathematicDiscrete mathematic
Discrete mathematic
Naralaswapna
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
Emertxe Information Technologies Pvt Ltd
 
Set operations in python (Dutch national flag and count &say problem).pptx
Set operations in python (Dutch national flag and count &say problem).pptxSet operations in python (Dutch national flag and count &say problem).pptx
Set operations in python (Dutch national flag and count &say problem).pptx
murasolimathavi
 
ARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptxARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptx
DarellMuchoko
 
mathematical sets.pdf
mathematical sets.pdfmathematical sets.pdf
mathematical sets.pdf
Jihudumie.Com
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
chin463670
 

Similar to Set methods in python (20)

Set data structure
Set data structure Set data structure
Set data structure
 
Question In C Programming In mathematics, a set is a colle...Sav.pdf
Question In C Programming In mathematics, a set is a colle...Sav.pdfQuestion In C Programming In mathematics, a set is a colle...Sav.pdf
Question In C Programming In mathematics, a set is a colle...Sav.pdf
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
Blackbox task 2
Blackbox task 2Blackbox task 2
Blackbox task 2
 
Python_Sets(1).pptx
Python_Sets(1).pptxPython_Sets(1).pptx
Python_Sets(1).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
Set relationship, set operation and sigmoid
Set relationship, set operation and sigmoidSet relationship, set operation and sigmoid
Set relationship, set operation and sigmoid
 
Java
JavaJava
Java
 
sets and maps
 sets and maps sets and maps
sets and maps
 
Python Sets_Dictionary.pptx
Python Sets_Dictionary.pptxPython Sets_Dictionary.pptx
Python Sets_Dictionary.pptx
 
07012023.pptx
07012023.pptx07012023.pptx
07012023.pptx
 
package lab7 public class SetOperations public static.pdf
package lab7     public class SetOperations  public static.pdfpackage lab7     public class SetOperations  public static.pdf
package lab7 public class SetOperations public static.pdf
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Discrete mathematic
Discrete mathematicDiscrete mathematic
Discrete mathematic
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Set operations in python (Dutch national flag and count &say problem).pptx
Set operations in python (Dutch national flag and count &say problem).pptxSet operations in python (Dutch national flag and count &say problem).pptx
Set operations in python (Dutch national flag and count &say problem).pptx
 
ARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptxARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptx
 
mathematical sets.pdf
mathematical sets.pdfmathematical sets.pdf
mathematical sets.pdf
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
 

More from deepalishinkar1

Operators in python
Operators in pythonOperators in python
Operators in python
deepalishinkar1
 
Data handling in python
Data handling in pythonData handling in python
Data handling in python
deepalishinkar1
 
Practical approach on numbers system and math module
Practical approach on numbers system and math modulePractical approach on numbers system and math module
Practical approach on numbers system and math module
deepalishinkar1
 
Demonstration on keyword
Demonstration on keywordDemonstration on keyword
Demonstration on keyword
deepalishinkar1
 
Numbers and math module
Numbers and math moduleNumbers and math module
Numbers and math module
deepalishinkar1
 
Basic concepts of python
Basic concepts of pythonBasic concepts of python
Basic concepts of python
deepalishinkar1
 
Introduction to python
Introduction to python Introduction to python
Introduction to python
deepalishinkar1
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
deepalishinkar1
 

More from deepalishinkar1 (8)

Operators in python
Operators in pythonOperators in python
Operators in python
 
Data handling in python
Data handling in pythonData handling in python
Data handling in python
 
Practical approach on numbers system and math module
Practical approach on numbers system and math modulePractical approach on numbers system and math module
Practical approach on numbers system and math module
 
Demonstration on keyword
Demonstration on keywordDemonstration on keyword
Demonstration on keyword
 
Numbers and math module
Numbers and math moduleNumbers and math module
Numbers and math module
 
Basic concepts of python
Basic concepts of pythonBasic concepts of python
Basic concepts of python
 
Introduction to python
Introduction to python Introduction to python
Introduction to python
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
 

Recently uploaded

Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 

Recently uploaded (20)

Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 

Set methods in python

  • 1. SET
  • 2. SET • A set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable (which cannot be changed). • However, the set itself is mutable. We can add or remove items from it. • Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc.
  • 3. Creating SET • A set is a collection which is unordered and unindexed. • A set iss created by placing all the items(elements) inside with curly brackets{},separated by comma or by using the built-in function set(). • It can have any number of items and they may be of different types (integer, float, tuple, string etc.). • Empty curly braces {} will make an empty dictionary in Python. • To make a set without any elements we use the set() function without any argument.
  • 4. Creating SET • Important : But a set cannot have a mutable element, like list, set or dictionary, as its element. Example : set_four={1,2,[3,4]} print set_four #output : set_four={1,2,[3,4]} TypeError: unhashable type: 'list’Because Set is immutable and list is mutable so we can’t contain list in set.
  • 5. Creating SET • We can make set from a list. my_set = set([1,2,3,2]) print(my_set) #Output : {1, 2, 3}
  • 6. Access Items • You cannot access items in a set by referring to an index, since sets are unordered the items has no index. • But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword. thisset = {“sad", “happy", “love“,”hate”} for x in thisset: print(x) # Output : sad happy love hate
  • 7. Change SET methods • To add one item to a set use the add( ) method. • To add more than one item to a set use the update() method. • The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.
  • 8. Remove element from SET • A particular item can be removed from set using methods, discard() and remove(). • The only difference between the two is that, while using discard() if the item does not exist in the set, it remains unchanged. But remove() will raise an error in such condition. • You can also use the pop(), method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed. The return value of the pop() method is the removed item. • The clear() method empties the set. • The del keyword will delete the set completely.
  • 10. Union( ) • Union operation is performed using | operator. Same can be accomplished using the method union(). Union of sets is a set of all elements from both A & B sets. # set operations A = {1, 3, 5, 7, 9} B = {2, 4, 6,8,10} print(A|B) print(A.union(B)) print(B.union(A)) #Above all print statement output will be same. #Output :{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  • 11. Intersection( ) • Intersection operation is performed using & operator. Same can be accomplished using the method intersection(). Intersection of sets is a set of elements that are common in both sets. # set operations A = {1, 3, 4, 7, 8} B = {2, 4, 3,8,10} print(A&B) print(A.intersection(B)) print(B.intersection(A)) #Above all print statement output will be same. #Output :{3,4,8}
  • 12. Difference( ) • Difference is performed using - operator. Same can be accomplished using the method difference(). Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a set of element in B but not in A. # set operations A = {1, 3, 4, 7, 8} B = {2, 4, 3,8,10} print(A-B) print(A. difference(B)) #output :{1, 7} print(B-A) print(B.difference(A)) #output :{2,10}
  • 13. symmetric_difference( ) • Symmetric Difference of A and B is a set of elements in both A and B except those that are common in both. Symmetric difference is performed using ^ operator. Same can be accomplished using the method symmetric_difference(). # set operations A = {1, 3, 4, 7, 8} B = {2, 4, 3,8,10} print(A^B) print(A. symmetric_difference(B)) print(B^A) print(B. symmetric_difference (A)) #Above all print statement output will be same. #output :{1,2,7,10}
  • 14. Copy( ) • The copy() method copies the set. fruits = {"apple", "banana", "cherry"} x = fruits.copy() print(x)
  • 15. difference_update( ) • The difference_update() method removes the items that exist in both sets. • The difference_update() method is different from the difference() method, because the difference() method returns a new set, without the unwanted items, and the difference_update() method removes the unwanted items from the original set. • Syntax : • A.difference_update(B) • Here, A and B are two sets. The difference_update() updates set A with the set difference of A-B. • The difference_update() returns None indicating the object (set) is mutated.
  • 16. difference_update( ) • Example: A = {'a', 'c', 'g', 'd'} B = {'c', 'f', 'g'} result = A.difference_update(B) print('A = ', A) print('B = ', B) print('result = ', result) #output: ( 'A = ', set(['a', 'd'])) ('B = ', set(['c', 'g', 'f'])) ('result = ', None) A = {'a', 'c', 'g', 'd'} B = {'c', 'f', 'g'} result = B.difference_update(A) print('A = ', A) print('B = ', B) print('result = ', result) #output: ('A = ', set(['a', 'c', 'd', 'g'])) ('B = ', set(['f'])) ('result = ', None)
  • 17. symmentric_difference_update( ) • The symmetric_difference_update() method finds the symmetric difference of two sets and updates the set calling it. • Syntax : • A.symmetric_difference_update(B) • The symmetric_difference_update() returns None (returns nothing). Rather, it updates the set calling it.
  • 18. symmentric_difference_update( ) Example: A = {'a', 'c', 'd'} B = {'c', 'd', 'e’ } result=A.symmetric_difference_update(B) print('A =', A) print('B =', B) print('result =', result) Output : A = {'a', 'e'} B = {'d', 'c', 'e'} result = None
  • 19. intersection_update( ) • The intersection of two or more sets is the set of elements which are common to all sets. • Syntax: • A.intersection_update(*other_sets) • The intersection_update() allows arbitrary number of arguments (sets). • This method returns None (meaning, absence of a return value). It only updates the set calling the intersection_update() method. This method returns None (meaning, absence of a return value). It only updates the set calling the intersection_update() method.
  • 20. intersection_update( ) Example : A = {1, 2, 3, 4} B = {2, 3, 4, 5, 6} C = {4, 5, 6, 9, 10} result = C.intersection_update(B, A) print('result =', result) print('C =', C) print('B =', B) print('A =', A) #Output : result = None C = {4} B = {2, 3, 4, 5, 6} A = {1, 2, 3, 4}
  • 21. issubset( ) • The issubset( ) method returns True if all elements of a set are present in another set (passed as an argument). If not, it returns False. • Set A is said to be the subset of set B if all elements of A are in B. • Syntax: • A.issubset(B) • The issubset() returns ✓True if A is a subset of B ✓False if A is not a subset of B
  • 22. issuperset( ) • The issuperset() method returns True if all items in the specified set exists in the original set, otherwise it retuns False. • Syntax: • A.issuperset(B) • The issuperset() returns ✓ True if A is a superset of B # Return True if all items in set B are present in set A. ✓ False if A is not a superset of B # Return False if not all items in set B are present in set A.
  • 23. issubset( ) • Example : A = {1, 2, 3} B = {1, 2, 3, 4, 5} C = {1, 2, 4, 5} print(A.issubset(B)) print(B.issubset(A)) print(A.issubset(C)) print(C.issubset(B)) Output: True False False True
  • 24. disjoint( ) • The isdisjoint() method returns True if two sets are disjoint sets. If not, it returns False. • Two sets are said to be disjoint sets if they have no common elements. • Syntax: • A.disjoint( ) • The isdisjoint() method returns ✓ True if two sets are disjoint sets ✓ (if set_a and set_b are disjoint sets in above syntax) ✓ False if two sets are not disjoint sets
  • 25. len( ),set( ) • To determine how many items a set has, use the len() method. • Syntax: len(set_name) • It is also possible to use the set() constructor to make a set. • Example: thisset = set(("apple", "banana", "cherry")) # note the double round-brackets print(thisset)