डिप्लोमा इन ऑफिस मैनेजमेंट एण्ड अकाउटिंग

डिप्लोमा इन ऑफिस मैनेजमेंट एण्ड अकाउटिंग

Full Stack Web Development with Laravel

Full Stack Web Development with Laravel

Affiliate Program

Affiliate Program

Python Set

Collection of items, in set items are stored in curly { } brackets.
s = {1, 2, 3}
Note: set are unordered, unindexed, and mutable, also it does not allow duplicate values like tuple, list
 

Access set 

s = {1, 2, 3}
print(s)

Access set items

for item in s:
print(item)
 

Set methods

add() Add single item to set
s={1, 2, 3}
s.add(4)
print(s) # {1, 2, 3, 4}
update() Add multiple items to set
s={1, 2, 3}
s.update(4, 5)
print(s) # {1, 2, 3, 4, 5}
remove() Remove item from set, raise an error when item not found
s={1, 2, 3}
s.remove(2)
print(s) # {1, 3}
discard() Remove item from set, and does not raise an error when item not found
s={1, 2, 3}
s.remove(3)
print(s) # {1, 2}
clear() Remove all items from a set
s={1, 2, 3}
s.clear()
print(s) # {}
pop() Remove an element from a set
s={1, 2, 3}
s.pop
print(s) # will remove any item from a set
difference() Return set of difference of two set(set of items of A which are not in B)
x={1, 2, 3}
y={3, 4, 5}
print( x.difference(y) ) # {1, 2}
intersection() Return intersection set of two set (set of common items from set A, B)
x={1, 2, 3}
y={3, 4, 5}
print( x.intersection(y) ) # {3}
union() Return set of all items from set A, B
x={1, 2, 3}
y={3, 4, 5}
print( x.union(y) ) # {1, 2, 3, 4, 5}
issubset() Return true if one set is subset of other set otherwise false
x={1, 2, 3}
y={3}
print( y.issubset(x) ) # True
copy() Return copy of a set
x={1, 2, 3}
y=x.copy()
print( y ) # {1, 2, 3}
© 2016 - 2023, All Rights are Reserved.