Python Sets: A Quick Guide
1. What is a Set?
A set is an unordered, mutable collection of unique elements.
2. Creating Sets
# Set with elements
my_set = {1, 2, 3, 4}
print(my_set)
# Output: {1, 2, 3, 4}
# Empty set
empty_set = set()
print(empty_set)
# Output: set()
# Note: {} creates an empty dictionary, not a set
3. Adding and Removing Elements
s = {1, 2, 3}
# Add element
[Link](4)
print(s)
# Output: {1, 2, 3, 4}
# Remove element
[Link](2)
print(s)
# Output: {1, 3, 4}
# Discard element (no error if not found)
[Link](10)
print(s)
# Output: {1, 3, 4}
# Clear set
[Link]()
print(s)
# Output: set()
1
4. Set Operations
a = {1, 2, 3}
b = {3, 4, 5}
# Union
print(a | b)
# Output: {1, 2, 3, 4, 5}
# Intersection
print(a & b)
# Output: {3}
# Difference
a - b
# Output: {1, 2}
b - a
# Output: {4, 5}
# Symmetric Difference
print(a ^ b)
# Output: {1, 2, 4, 5}
5. Other Useful Methods
s = {1, 2, 3}
print(len(s)) # Output: 3
print(2 in s) # Output: True
[Link]([4, 5]) # Add multiple elements
print(s) # Output: {1, 2, 3, 4, 5}
[Link]() # Remove random element
print(s) # Output: Remaining elements
6. Example with Duplicate Values
fruits = {"apple", "banana", "mango", "apple"}
print(fruits)
# Output: {'banana', 'apple', 'mango'} (duplicates removed)
Summary: - {} = empty dictionary - set() = empty set - Sets store unique elements - Support
union, intersection, difference, symmetric difference - Mutable but unordered