Python Sets
Sets are an unordered collection of unique elements in Python. They are useful for removing duplicates and performing mathematical operations like union and intersection.
Creating a Set
# Creating a set
fruits = {"apple", "banana", "cherry"}
print(fruits)
Adding and Removing Elements
favorites = {"chocolate", "vanilla"}
# Adding an element
favorites.add("strawberry")
# Removing an element
favorites.remove("vanilla")
print(favorites)
Set Operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Union
print(a & b) # Intersection
print(a - b) # Difference
print(a ^ b) # Symmetric Difference
Checking Membership
numbers = {10, 20, 30, 40}
if 20 in numbers:
print("20 is in the set")
Looping Through a Set
colors = {"red", "green", "blue"}
for color in colors:
print(color)
Converting a List to a Set
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers) # Output: {1, 2, 3, 4, 5}
Set Methods
names = {"Alice", "Bob", "Charlie"}
names.update(["David", "Eve"])
names.discard("Alice")
print(names)
Conclusion
Sets are powerful for handling unique values and performing fast operations. They are widely used in data processing and mathematical computations.