Python Sets
§ A set is an unordered collection of
items.
§ Every element is unique and must be
immutable.
§ Python sets are mutable; you can add
and remove items from it.
Creating a Set
ØA set is created by placing all the
elements inside curly braces {},
separated by comma or by using the
built-in function set().
ØThe elements can be of different types
(integer, float, tuple, string etc.).
Creating a Set
ØBut a set cannot have a mutable
element, like list, set or dictionary, as
its element.
Creating a Set
Creating a Set
1)creating set :
Creating a Set
2)Using set( ) constructor :
Python Sets
3)Empty set consider as dictionary
Python Mathematical operations
ØSets can be used to perform
mathematical set operations like:
Ø Union
Ø Intersection
Ø difference
Ø symmetric difference
Python Set Operations
Ø We can do this with operators or methods.
Set Operations
If A and B are two python sets:
1)Union
Set Operations
If A and B are two python sets:
2)INTERSECTION (&)
Set Operations
3)DIFFERENCE (-)
Set Operations
4) symmetric difference (^)
Adding elements to a set
ØSets are mutable. But since they are
unordered, indexing have no meaning.
ØWe cannot access or change an element
of set using indexing or slicing.
Adding elements to a set
Ø We can add single element using the add() method and
multiple elements using the update()method.
ü add() for single elements
ü update() for iterable
Ø The update() method can take tuples, lists, strings
or other sets as its argument.
Duplicates in set
Ø In all cases, duplicates are avoided.
Adding a values to set
1) add( )
Adding a new values to set
2) update( )
integer value
Adding a new values to set
2) update( )
Adding a new values to set
2) update( )
Adding a new values to set
2)Update()
Operation in set
1) len( )
Find the length of the set.
Operation in set
2) remove( )
Operation in set
3)discard( )
Operation in set
Operation in set
Ø pop( )
Frozen Set
Ø A frozen set is just like a normal set, but it is
immutable, meaning
➡️You cannot add, remove, or modify its
elements after creation.
Ø It is useful when you need a fixed set of items
that should not change and can be used as a
dictionary key or an element of another set.
Frozen set
Ø A = frozenset([1, 2, 3, 4])
Properties
Ø Unordered
Ø No duplicates
Ø Immutable (cannot be changed after
creation)
Ø Hashable (can be used as dictionary
keys)
Hashable Types:
ØInt
ØFloat
ØString
ØTuple
ØFrozenset
Non-hashable (Unhashable) Types:
ØList
ØDictionary
Øset