what are basic set operations in python?
The union of two sets returns a new set containing all elements that are in either set.
A = {1, 2, 3}
B = {3, 4, 5}
union_set = A | B # {1, 2, 3, 4, 5}
# or
union_set = A.union(B) # {1, 2, 3, 4, 5}
The intersection of two sets returns a new set containing all elements that are in both sets.
A = {1, 2, 3}
B = {3, 4, 5}
intersection_set = A & B # {3}
# or
intersection_set = A.intersection(B) # {3}
The difference of two sets returns a new set containing elements that are in the first set but not in the second.
A = {1, 2, 3}
B = {3, 4, 5}
difference_set = A - B # {1, 2}
# or
difference_set = A.difference(B) # {1, 2}
The symmetric difference of two sets returns a new set containing elements that are in either of the sets, but not in both.
A = {1, 2, 3}
B = {3, 4, 5}
sym_diff_set = A ^ B # {1, 2, 4, 5}
# or
sym_diff_set = A.symmetric_difference(B) # {1, 2, 4, 5}
Subset and Superset
A = {1, 2}
B = {1, 2, 3}
is_subset = A <= B # True
# or
is_subset = A.issubset(B) # True
A = {1, 2, 3}
B = {1, 2}
is_superset = A >= B # True
# or
is_superset = A.issuperset(B) # True
Add an element:
A = {1, 2, 3}
A.add(4) # A becomes {1, 2, 3, 4}
Remove an element: A.remove(x)
(raises KeyError
if x
is not in the set) or A.discard(x)
(does not raise an error if x
is not in the set)
A = {1, 2, 3}
A.remove(3) # A becomes {1, 2}
# or
A.discard(3) # A becomes {1, 2}
Check membership
A = {1, 2, 3}
is_member = 2 in A # True
These operations provide powerful tools for working with sets in Python, allowing for complex set-based manipulations and comparisons with simple, concise syntax.
"Answer Generated by OpenAI's ChatGPT"