Learn Python - Python tutorial - python sets - Python examples - Python programs
A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Python’s set class represents the mathematical notion of a set. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a speci?c element is contained in the set. This is based on a data structure known as a hash table.
Frozen Sets Frozen sets are immutable objects that only support methods and operators that produce a result without a?ecting the frozen set or sets to which they are applied.
python - Sample - python code :
Output:
1. add(x) Method: Adds the item x to set if it is not already present in the set.
python - Sample - python code :
-> This will add Daxit in people set.
2. union(s) Method: Returns a union of two set.Using the ‘|’ operator between 2 sets is the same as writing set1.union(set2)
python - Sample - python code :
OR
-> Set population set will have components of both people and vampire
3. intersect(s) Method: Returns an intersection of two sets.The ‘&’ operator comes can also be used in this case.
python - Sample - python code :
-> Set victims will contain the common element of people and vampire
4. difference(s) Method: Returns a set containing all the elements of invoking set but not of the second set. We can use ‘-‘ operator here.
python - Sample - python code :
OR
-> Set safe will have all the elements that are in people but not vampire
5. clear() Method: Empties the whole set.
python - Sample - python code :
-> Clears victim set
However there are two major pitfalls in Python sets:
- The set doesn’t maintain elements in any particular order.
- Only instances of immutable types can be added to a Python set.
Sets and frozen sets support the following operators:
key in s # containment check
key not in s # non-containment check
s1 == s2 # s1 is equivalent to s2
s1 != s2 # s1 is not equivalent to s2
s1 <= s2 # s1is subset of s2
s1 < s2 # s1 is proper subset of s2
s1 >= s2 # s1is superset of s2
s1 > s2 # s1 is proper superset of s2
s1 | s2 # the union of s1 and s2
s1 & s2 # the intersection of s1 and s2
s1 – s2 # the set of elements in s1 but not s2
s1 ˆ s2 # the set of elements in precisely one of s1 or s2
Code Snippet to illustrate all Set operations in Python
python - Sample - python code :
python tutorial - Output :