Common Set Methods
Python sets come with a variety of built-in methods that allow you to perform common set operations.
union()
Method
Returns a new set containing all unique elements from both sets.
update()
Method
Adds elements from another set or iterable to the existing set.
intersection()
Method
Returns a new set with elements common to both sets.
Example: Using intersection()
# Using intersection()
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection_set = set1.intersection(set2)
print("Intersection Set:", intersection_set)
Output
Intersection Set: {2, 3}
difference()
Method
Returns a new set with elements in the first set that are not in the second set.
symmetric_difference()
Method
Returns a new set with elements in either set but not in both.
issubset()
Method
Returns True
if all elements of the set are in another set.
Example: Using issubset()
# Using issubset()
small_set = {1, 2}
big_set = {1, 2, 3, 4, 5}
print("Is small_set a subset of big_set?", small_set.issubset(big_set))
Output
Is small_set a subset of big_set? True
Explanation: These methods help perform standard set operations like union, intersection, difference, and checking for subsets.