Ad – 728Γ—90
πŸ“¦ Data Structures

Python Sets – Unique Collections with Set Operations

A set is an unordered collection of unique elements. Sets automatically eliminate duplicates, support mathematical set operations (union, intersection, difference), and provide O(1) membership testing β€” much faster than lists for checking if an item exists.

⏱️ 18 min read 🎯 Beginner πŸ“… Updated 2026

Creating Sets

Use curly braces {} or the set() constructor. Note: {} creates an empty dict, not a set β€” use set() for an empty set.

Python
# Creating sets
fruits = {"apple", "banana", "cherry", "apple"}  # Duplicate removed!
print(fruits)  # Order not guaranteed!

numbers = set([1, 2, 3, 2, 1])  # From list
print(numbers)  # {1, 2, 3}

empty_set = set()  # NOT {} (that's a dict!)
print(type(empty_set))  # 
β–Ά Output
{'cherry', 'banana', 'apple'} {1, 2, 3}

Adding and Removing Elements

add(), remove(), discard(), pop(), and clear() modify sets in-place.

Python
s = {1, 2, 3}

s.add(4)          # Add single element
print(s)          # {1, 2, 3, 4}

s.remove(2)       # Remove - raises KeyError if not found
s.discard(99)     # Remove - no error if not found
print(s)          # {1, 3, 4}

popped = s.pop()  # Remove and return arbitrary element
print(popped)
β–Ά Output
{1, 2, 3, 4} {1, 3, 4} 1
Ad – 336Γ—280

Set Operations – Union, Intersection, Difference

Sets support mathematical operations. These are the most useful feature of sets.

Python
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}

print(a | b)    # Union: all elements from both: {1,2,3,4,5,6,7,8}
print(a & b)    # Intersection: elements in BOTH: {4, 5}
print(a - b)    # Difference: in a but NOT b: {1, 2, 3}
print(a ^ b)    # Symmetric diff: in one but not both: {1,2,3,6,7,8}
β–Ά Output
{1, 2, 3, 4, 5, 6, 7, 8} {4, 5} {1, 2, 3} {1, 2, 3, 6, 7, 8}

Fastest Way to Test Membership

Sets provide O(1) membership testing β€” far faster than lists for large collections.

Python
import time

big_list = list(range(1000000))
big_set = set(range(1000000))

# Both find the same element, but set is ~100x faster
print(999999 in big_list)  # True (slow - O(n))
print(999999 in big_set)   # True (fast - O(1))

# Common use: remove duplicates from a list
duplicates = [1, 2, 3, 2, 4, 3, 5, 1]
unique = list(set(duplicates))
print(unique)
β–Ά Output
True True [1, 2, 3, 4, 5]