A set is an unordered collection of unique elements in Python. Sets are mutable but do not allow duplicate values. They support operations like union, intersection, difference, and symmetric difference.
my_set = {1, 2, 3}
empty_set = set() # Note: {} creates an empty dictionary, not a set
# 1. Creating and printing a set
fruits = {"apple", "banana", "cherry"}
print(fruits) # Output: {'banana', 'apple', 'cherry'}
# 2. Adding elements to a set
fruits.add("orange")
print(fruits)
# 3. Removing elements from a set
fruits.remove("banana")
print(fruits)
# 4. Set operations: union and intersection
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # Output: {1, 2, 3, 4, 5}
print(a.intersection(b)) # Output: {3}
# 5. Checking membership
print("apple" in fruits) # Output: True or False depending on current set contents