It is a collection of unordered items. each element in the set must be unique, immutable and the set removes the duplicate elements.
Creating a Set:
The set can be created by enclosing the comma-separated immutable items with the curly braces {}.
Python also provides the set() method, which can be used to create the set by the passed sequence.
day={1,2,3,4,5,6}
Creating empty set:
s={}, it creates empty dictionary.
s=set()
Add item to the list:
Add(): It is used to add a single item to the set.
day={1,2,3,4,5,6}
day.add(9)
day
Update(): It is used to add multiple item to set.
Remove item from the list: Remove() and Discard()
Remove(): It will throw an error if the item doesn't exist.
day={1,2,3,4,5,6}
day.remove(9)
day
Discard(): It will not throw an error if the item doesn't exist.
day={1,2,3,4,5,6}
day.discard(9)
day
Set Operation:
- union
- Intersection
- Difference
- Symmetric difference: Present in one set or the other but not in both sets.
1.
s1={1,2,3,4,5,6}
s2={3,4,5,6,7,9,10}
print(s1^s2)
2.
s1={1,2,3,4,5,6}
s2={3,4,5,6,7,9,10}
print(s1.symmetric_difference(s2))
Set Comparison
Equal Operator: checks if two sets have the same elements, regardless of their order.
a={4,5}
b={4,5,6,7,8}
print(a==b)
Not Equal Operator: checks if two sets are not equal.
a={4,5}
b={4,5,6,7,8}
print(a!=b)
< : checks if the left set is a proper subset of the right set
a={4,5}
b={4,5,6,7,8}
print(a<b)
<=: checks if the left set is a subset of the right set.
a={4,5}
b={4,5,6,7,8}
print(a<=b)
>:checks if the left set is a proper superset of the right set.
a={4,5}
b={4,5,6,7,8}
print(a>b)
>=: checks if the left set is a superset of the right set
a={4,5}
b={4,5,6,7,8}
print(a>=b)
Frozen Sets: It is an immutable version of the built. It is similar to a set, but its contents cannot be changed once a frozen set is created.
Frozen set objects can be used as elements of other sets or dictionary keys, while standard sets cannot.
We can use a frozen set as a key in dictionaries or as an element of another set.
fs=frozenset([1,2,3,4,5,6])
fs
fs.add(9)