Sets 114657
Sets 114657
Frozen set:
• A frozen set in python is a set whose values cannot be modified.
• Frozen sets can be created using the frozenset() method.
Example:
a = {1,'a',4,9.5}
b = frozenset(a)
print(b)
Output: frozenset({1, 4, 'a', 9.5})
b.add(7)
print(b)
Output: AttributeError: 'frozenset' object has no attribute 'add'
Set Operations:
Function Description Example
add() Add a single element s = {5,9,0}
using the add() method. s.add(7)
Dduplicates are avoided print(s) #Output: {0, 9, 5, 7}
update() Add a multiple elements s = {5,9,0}
using the update() method. s.update([7,8,5,10])
The update() method can print(s) # Output: {0, 5, 7, 8, 9, 10}
take tuples, lists, strings or s.update([8,3], {1,6,8}) # add list &
other sets as its argument. set
Duplicates are avoided. print(s) # Output: {0, 1, 3, 5, 6, 7, 8,
9, 10}
remove() Remove a particular s = {5,9,0,'abc','def'}
element from a set. s.remove('abc')
Returns KeyError if print(s) # Output: {0, 5, 'def',
element is not present. 9}
s.remove(10)
print(s) # Output: KeyError:
10
discard() Same as remove() but s = {5,9,0,'abc','def'}
does not give an error if s.discard('abc')
element is not present in print(s) # Output: {0, 5, 'def',
the set. 9}
s.discard(10)
print(s) # Output: {0,5,’def’,9}
pop() Removes and returns any my_set = {1,'a',4,9.5}
arbitrary element from my_set.pop()
set. KeyError is raised if print(my_set) # Output: {4, 'a',
set is empty. 9.5}
clear() Removes all elements my_set = {1,'a',4,9.5}
from the set. my_set.clear()
print(my_set) # Output: set()
union() Return all the elements a = {1,'a',4,9.5}
from both the set. b = {10,20}
Union is also performed print(a|b) # Output: {1, 4, 'a', 9.5,
using “ | “ operator. 10, 20}
print(a.union(b)) #Output: {1, 4, 'a',
9.5, 10, 20}
intersection() or “&” Returns a new set that a = {1,'a',4,9.5}
has elements which are b = {1,10,20}
common in both the sets. print(a&b) # Output: {1}
print(a.intersection(b)) # Output: {1}
difference() or “-“ Returns a new set that a = {1,'a',4,9.5}
has elements in set a but b = {1,10,20}
not in set b. print(a-b) # Output: {9.5, 4,
'a'}
print(a.difference(b)) # Output: {9.5,
4, 'a'}
symmetric_difference() Returns a new set with a = {1,'a',4,9.5}
or “^” elements either in a or in b = {1,10,20}
b but not both. print(a^b) # Output: {4,9.5,10,'a',20}
print(a.symmetric_difference(b)) #
Output: {4,9.5,10,'a',20}
issubset() or “<=” Returns true if every a={4,7,9,'def',(3,'g')}
element in set a is present b={6,9,4,7,'def',(3,'g')}
in set b and false print(a.issubset(b)) # Output: True
otherwise. print(a<=b) # Output: True