Professional Documents
Culture Documents
Elements can be of different Behave differently when the Use the intersection method
data types specified item is not found in
the set Format: set1.intersection(set2)
Creating a Set
remove method raises a Use the & operator
set function: used to create a KeyError exception Format: set1 & set2
set
discard method does not raise Both techniques return a new
For empty set, call set() an exception set which contains the
For non-empty set, call clear method: clears all the intersection of both sets
set(argument) where argument elements of the set Finding the Difference of Sets
is an object that contains
iterable elements Using the for Loop, in, and Difference of two sets: a set
not in Operators with a Set that contains the elements
e.g., argument can be a list,
A for loop can be used to that appear in the first set but
string, or tuple
iterate over elements in a set do not appear in the second
If argument is a string, each set
character becomes a set General format: for item in set:
To find the difference of two
element The loop iterates once for each sets:
For set of strings, pass them to element in the set
Use the difference method
the function as a list The in operator can be used
to test whether a value exists Format: set1.difference(set2)
in a set
Use the - operator Set A is superset of set B if it
contains all the elements of
Format: set1 - set2
set B
Finding the Symmetric
To determine whether set A
Difference of Sets
is superset of set B
Symmetric difference of two Use the issuperset method
sets: a set that contains the
elements that are not shared Format: setA.issuperset(setB)
by the two sets
Use the >= operator
To find the symmetric
Format: setA >= setB
difference of two sets:
Serializing Objects
Use the symmetric_difference
method Serialize an object: convert
the object to a stream of
Format:
bytes that can easily be
set1.symmetric_difference(set2
stored in a file
)
Pickling: serializing an object
Use the ^ operator
Format: set1 ^ set2 To pickle an object: Import
the pickle module
Finding Subsets and
Open a file for binary writing
Supersets
Call the pickle.dump function
Set A is subset of set B if all
the elements in set A are Format: pickle.dump(object,
included in set B file)
To determine whether set A Close the file
is subset of set B
You can pickle multiple
Use the issubset method objects to one file prior to
closing the file
Format: setA.issubset(setB)
Use the <= operator Unpickling: retrieving pickled
object
Format: setA <= setB
To unpickle an object:
Import the pickle module
Open a file for binary writing
Call the pickle.load function
Format: pickle.load(file)
Close the file
You can unpickle multiple
objects from the file