5.4. Sets
A Set in Python is used to store a collection of items with the following properties.
🡆N duplicate elements.If try to insert the same item again, it overwites previous one.
🡆An unordered collection.When we access all items, they are accessed without any specific order and we cannot access items using indexes as we do in lists.
🡆Internally use Hashing that makes set efficient for search, insert and delete operations.
Mutable, meaning we can add or remove elements after their creation.the individual elements within the set cannot be changed directly.
There is No specific order for set elements to be printed
Example of Python Sets
s = {10, 50,20}
print(s)
print(type(s))
Output:
{10, 50, 20}
<class ‘set’
Type Casting with Python Set method
s= set ([“a” ,”b”,”c”])
print(s)
#Adding elements.add(“d”)
s.add(“d)
print(s
Output
{‘c’, ‘b’, ‘b’}
{‘d’,’c’,’b’,’a’
🡆Python Frozen Sets:Frozen sets in python are immutable objects that only support methods and operators that produce a result without affecting the frozen sets to which they are applied.It can be done with frozensset() method in Python.
🡆Internal working of set:This is based on a data structure known a hash table. If Multiple values are presented at the same index position,then the value is appended to that index position to form a Linked list.
🡆Methods for Sets:Insertion in the set is done through the set.add() function,Where an appropriate record value is created to store in the hash table.
Two sets can merged using union() function or | operator.Both Hash table values are accessed and traversed with merge operation performed on them to combine the elements at the same time duplicates are removed.
They are similar to iteration over the Hash lists and combining the same values on both the table.
