Topic 25 of 58
Sets
Overview
Sets are unordered collections of UNIQUE elements. Under the hood, sets are implemented using Hash Tables. This structural design makes checking if an item exists within a set an incredibly fast O(1) constant time operation, compared to scanning a list which takes O(N) linear time. Sets are the ultimate weapon in coding interviews for quickly removing duplicates from data or tracking 'seen' elements to prevent infinite loops in graph traversals.
Syntax
python
# Creating a Set (Automatically discards duplicates)
unique_nums = {1, 2, 3, 3, 3}
print(unique_nums) # {1, 2, 3}
# Modifying Sets
unique_nums.add(4)
unique_nums.remove(2) # Throws KeyError if 2 isn't found
unique_nums.discard(99) # Safely removes, does nothing if 99 isn't found
# Lightning fast O(1) lookup
print(3 in unique_nums) # True
# Mathematical Set Operations
group_a = {1, 2, 3}
group_b = {3, 4, 5}
print(group_a | group_b) # Union (All unique): {1, 2, 3, 4, 5}
print(group_a & group_b) # Intersection (Only shared): {3}Common Pitfalls
- Attempting to create an empty set with
{}. Because dictionaries were added to Python first,{}creates an empty dictionary. You MUST useset()to create an empty set. - Trying to access items by an index (e.g.,
my_set[0]). Sets have no concept of order, so indexing will throw a TypeError.
Interview Questions
Q:
How can you instantly remove all duplicates from a list?
A:
By passing the list through a set constructor, and then converting it back to a list: unique_list = list(set(raw_list)).
Real-World Example
Optimizing a search operation on a massive dataset.
example
python
allowed_ips = ["192.168.1.1", "10.0.0.1", "172.16.0.1"] # Imagine 100,000 IPs
# Convert to set ONCE for fast lookups
ip_set = set(allowed_ips)
incoming_ip = "10.0.0.1"
# This lookup happens instantly (O(1)), regardless of the set size
if incoming_ip in ip_set:
print("Connection Accepted")Check Your Knowledge
Test your understanding of Sets with these quick questions.