Set in Python

Set in Python

Set is a data type in Python that stores only Unique Value and placed in Curly Brackets {}.
We can not be sure in the sequence of Set! The reason is Set, use the concept of hash, using hash we improve the performance, we want to fetch the element as fastest as possible So it simply says ok go with this flow.
In Set Indexing is not supported! because we don't have a proper sequence or its unorder that why we can't Iterate it. 


myset = {1, 3, 5, 8, 4, 'jai', 'mahakal', 15}
st = [3, 23, 4, 54, 2]
s = set(st)                                     # set() used to convert in set datatype
s.add(38)                                       # add() used to add element in set
s.remove(3)                               # remove() used to remove element from set   
print(type(myset))                        # type() used to know , which datatype is it!
print(type(s))

myset = s.union({38, 43})                            # union adds up two sets
myset = s.intersection({2, 3, 4, 5, 8})         # intersection tell us common value in two sets
print('',s ,'\n', myset)
print(myset.difference(st))                      # difference is used to know the diff btw two Sets


''' Program : Removing Duplicates Values from List Using Set '''
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "Akash", 2, 4, 7, 12, 47, "kumar", "Singh", "Akash"]
a = set(lst)                             # Converting list into set so that it's print unique values in list
no_duplicate_list = list(a)
print("There are unique value in list : ", no_duplicate_list)




Disqus Comments