Set Data Structure
By:
Dr. Nand Kumar Jyotish, Assistant Professor,
CSE, MNIT Jaipur
Set Data Structure
If we want to represent a group of unique values as a single entity, then
we should go for a set.
Duplicates are not allowed.
Insertion order is not preserved. But we can sort the elements.
Indexing and slicing are not allowed for the set.
Heterogeneous elements are allowed.
Set objects are mutable, i.e., once we create a set object, we can
perform any changes in that object based on our requirement.
We can represent set elements within curly braces and with
comma separation.
We can apply mathematical operations like union, intersection,
difference, etc., on set objects.
Creation of Set Objects:
We can create empty set object by using set() function as follows:
s = set()
The output is not in the same order of insertion.
Internally, these elements are saved on hash-based.
Hash value is never going to change. Therefore,
output {40, 10, 20, 30} will always be same.
print(s[0]) // output: TypeError: ‘set’ object does
not support indexing.
print(s[0:5]) // output: TypeError: ‘set’ object is not
subscriptable.
We can convert any sequence into a set as follows:
s = set (any sequence)
Membership operators: (in , not in)
Eg:
1. s=set("michael")
2. print(s)
3. print('c' in s)
4. print('z' in s)
5.
6. Output
7. {'c', 'h', 'i', 'm', 'a', 'l', 'e'}
8. True
9. False