Creating Sets and Basic Operations
A set is an unordered collection of unique elements. Sets automatically eliminate duplicates and are useful when you need to track unique items or perform mathematical set operations.
Sets are defined using curly braces {} or the set() constructor. Note that an empty set must be created with set(), not {} — empty curly braces create an empty dictionary.
Example
# Creating sets
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 2, 3, 3, 3]) # Duplicates removed
print(numbers) # {1, 2, 3}
empty_set = set() # NOT {} — that creates a dict
# Adding and removing
fruits.add("date")
fruits.discard("banana") # Remove if exists (no error if missing)
fruits.remove("cherry") # Remove (raises KeyError if missing)
print(fruits) # {'apple', 'date'}
# Checking membership (very fast in sets)
print("apple" in fruits) # True
print("banana" in fruits) # False
# Remove duplicates from a list
names = ["Alice", "Bob", "Alice", "Charlie", "Bob"]
unique_names = list(set(names))
print(unique_names) # ['Alice', 'Bob', 'Charlie'] (order may vary) - .add(item) — Add a single item to the set
- .remove(item) — Remove an item (raises KeyError if not found)
- .discard(item) — Remove an item (no error if not found)
- .pop() — Remove and return an arbitrary item
- .clear() — Remove all items from the set
- len(set) — Number of items in the set
Try Sets
JavaScript
# Remove duplicates
names = ["Alice", "Bob", "Alice", "Charlie", "Bob"]
unique = set(names)
print("Original list:", names)
print("Unique set:", unique)
print("Count:", len(unique))
# Add and remove
unique.add("Dave")
unique.discard("Bob")
print("Modified:", unique) Notes
- Sets are optimized for membership testing. Checking if an item is in a set is O(1) on average, while checking in a list is O(n). Use sets when you need fast lookups.
Set Operations: Union, Intersection, Difference
Sets support mathematical set operations, making them perfect for comparing groups of data. You can find common elements, combine sets, or find differences between them.
These operations can be performed using methods or operators.
Example
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
# Union — all elements from both sets
print(a | b) # {1, 2, 3, 4, 5, 6, 7, 8}
print(a.union(b)) # Same result
# Intersection — elements in both sets
print(a & b) # {4, 5}
print(a.intersection(b))# Same result
# Difference — elements in a but not in b
print(a - b) # {1, 2, 3}
print(a.difference(b)) # Same result
# Symmetric difference — elements in either but not both
print(a ^ b) # {1, 2, 3, 6, 7, 8}
print(a.symmetric_difference(b)) # Same result
# Subset and superset
print({1, 2}.issubset(a)) # True
print(a.issuperset({1, 2})) # True
print(a.isdisjoint(b)) # False (they share elements) Try Set Operations
JavaScript
python_devs = {"Alice", "Bob", "Charlie", "Dave"}
js_devs = {"Charlie", "Dave", "Eve", "Frank"}
print("Python devs:", python_devs)
print("JS devs:", js_devs)
print("Both:", python_devs & js_devs)
print("All devs:", python_devs | js_devs)
print("Python only:", python_devs - js_devs)
print("JS only:", js_devs - python_devs) Notes
- Frozensets (frozenset()) are immutable sets. They can be used as dictionary keys or as elements of other sets, unlike regular sets.
