Set Operations in Python programming
python
Python is a high-level Programming language used to communicate with system. It’s a oops oriented,interperted,platform independent language, making it versatile and widely used across different domains.
set
Introduction:
Get Indiralaharshavardhan’s stories in your inbox
Join Medium for free to get updates from this writer.
A set is a built-in data structure in Python. It is an unordered collection of unique elements. Defined using curly braces {}.
# Example
set_1 = {2,3,4}
set_2={4, 5, 6}Set Operations
- Union
- Intersection Difference
- Symmetric Difference
- Subset/Superset
- Disjoint
Union
The union of two sets combines all elements without duplicates.
print(set_1|set_2)
print(set_1.union(set_2))
#output
#{2, 3, 4, 5, 6}
#{2, 3, 4, 5, 6}Intersection
The intersection finds elements common to both sets.
print(set_1 & set_2)
print(set_1.intersection(set_2))
# Output
# {4}
# {4}Difference
The difference shows elements in one set but not the other.
print(set_1 - set_2)
print(set_1.difference(set_2))
# Output
# {2, 3}
# {2, 3}
print(set_2 - set_1)
print(set_2.difference(set_1))
# Output
# {5, 6}
# {5, 6}Symmetric Difference
The symmetric difference includes elements in either set but not both.
print(set_1 ^ set_2)
print(set_1.symmetric_difference(set_2))
# Output
# {2, 3, 5, 6}
# {2, 3, 5, 6}Subset
Checks if all elements of one set are contained in another.
sub_set = {2, 3}
print(sub_set.issubset(set_1))
# Output
# TrueSuperset
Checks if a set contains all elements of another.
print(set_1.issuperset(small_set))
# Output
# TrueDisjoint
Checks if two sets have no elements in common.
set_3 = {7, 8}
print(set_1.isdisjoint(set_3))
# Output
# True



