A set is a built-in Python data structure that is unordered, mutable, and contains unique elements. Sets are useful for operations involving mathematical set theory, such as union, intersection, and difference.
1. Creating a Set
Sets are defined using curly braces {}
or the set()
function.
Example: Creating Sets
# Empty set (Must use set() because {} creates an empty dictionary)
empty_set = set()
# Set with numbers
numbers = {1, 2, 3, 4, 5}
# Set with mixed data types
mixed = {1, "hello", 3.14, True}
print(empty_set)
print(numbers)
print(mixed)
Output:
set()
{1, 2, 3, 4, 5}
{1, 'hello', 3.14}
Duplicate Elements Are Removed
duplicates = {1, 2, 2, 3, 4, 4, 5}
print(duplicates)
Output:
{1, 2, 3, 4, 5}
2. Accessing Set Elements
Sets do not support indexing because they are unordered. You can check membership using in
.
Example: Checking Membership
fruits = {"apple", "banana", "cherry"}
print("banana" in fruits) # True
print("grape" in fruits) # False
3. Adding and Removing Elements
(a) Adding Elements
fruits = {"apple", "banana"}
fruits.add("cherry") # Adds a single element
print(fruits)
(b) Updating a Set with Multiple Elements
fruits.update(["mango", "grape"])
print(fruits)
(c) Removing Elements
fruits.remove("banana") # Removes an element (raises error if not found)
fruits.discard("apple") # Removes an element (no error if not found)
print(fruits)
(d) Using pop()
to Remove Random Elements
removed_item = fruits.pop() # Removes a random element
print(removed_item)
(e) Clearing a Set
fruits.clear() # Removes all elements
print(fruits) # Output: set()
4. Set Operations
Python sets support union, intersection, difference, and symmetric difference.
(a) Union (|
or union()
)
Combines elements from both sets (removes duplicates).
A = {1, 2, 3}
B = {3, 4, 5}
union_set = A | B
print(union_set) # {1, 2, 3, 4, 5}
(b) Intersection (&
or intersection()
)
Finds common elements.
intersection_set = A & B
print(intersection_set) # {3}
(c) Difference (-
or difference()
)
Elements in A
but not in B
.
difference_set = A - B
print(difference_set) # {1, 2}
(d) Symmetric Difference (^
or symmetric_difference()
)
Elements in either set but not both.
symmetric_difference_set = A ^ B
print(symmetric_difference_set) # {1, 2, 4, 5}
5. Set Methods
Method | Description |
---|---|
add(x) | Adds x to the set |
remove(x) | Removes x (raises an error if not found) |
discard(x) | Removes x (no error if not found) |
pop() | Removes a random element |
clear() | Removes all elements |
union(set2) | Returns a new set containing all elements from both sets |
intersection(set2) | Returns common elements |
difference(set2) | Returns elements in the first set but not in the second |
symmetric_difference(set2) | Returns elements in either set but not both |
issubset(set2) | Checks if the set is a subset of another |
issuperset(set2) | Checks if the set is a superset of another |
6. Checking Subset and Superset
(a) issubset()
Returns True
if all elements of A
are in B
.
A = {1, 2}
B = {1, 2, 3, 4}
print(A.issubset(B)) # True
(b) issuperset()
Returns True
if A
contains all elements of B
.
pythonCopyEditprint(B.issuperset(A)) # True
7. Converting Between Lists and Sets
Sets automatically remove duplicates when converting from lists.
Example: Removing Duplicates from a List
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers) # {1, 2, 3, 4, 5}
Example: Convert Set to List
num_list = list(unique_numbers)
print(num_list) # [1, 2, 3, 4, 5]
8. Frozen Sets (Immutable Sets)
A frozenset is an immutable version of a set, meaning you cannot modify it after creation.
Example: Creating a Frozen Set
A = frozenset([1, 2, 3, 4])
print(A)
Allowed Operations on Frozen Sets
union()
,intersection()
,difference()
,symmetric_difference()
issubset()
,issuperset()
,copy()
Operations That Are Not Allowed
A.add(5) # Error: AttributeError: 'frozenset' object has no attribute 'add'
9. When to Use Sets?
Use sets when:
- You need unique elements (removing duplicates).
- You require fast lookups (checking membership).
- You are performing set operations (union, intersection, etc.).
Avoid sets when:
- Order is important (use lists instead).
- You need elements with index-based access (use lists or tuples).