#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
•Question 14 of 41easy

Sets in Python

Working with unique collections.

What You'll Learn

  • What sets are and when to use them
  • Set operations: union, intersection, difference
  • Adding, removing, and checking membership
  • Frozensets and practical use cases

Understanding Sets

Sets are unordered collections of unique elements. They're based on mathematical sets and excel at:

  • Removing duplicates
  • Fast membership testing (O(1))
  • Set operations (union, intersection, etc.)

Sets are defined with curly braces {} or the set() constructor.

Creating Sets

code.pyPython
# Empty set - MUST use set(), {} creates empty dict
empty = set()
not_empty_set = {}  # This is an empty DICT!

# Set with items
fruits = {"apple", "banana", "cherry"}

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

# From string
chars = set("hello")
print(chars)  # {'h', 'e', 'l', 'o'}

# Set comprehension
squares = {x**2 for x in range(5)}
print(squares)  # {0, 1, 4, 9, 16}

Set Operations

code.pyPython
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

# Union - elements in either set
a | b              # {1, 2, 3, 4, 5, 6}
a.union(b)         # Same result

# Intersection - elements in both sets
a & b              # {3, 4}
a.intersection(b)  # Same result

# Difference - elements in a but not in b
a - b              # {1, 2}
a.difference(b)    # Same result

# Symmetric Difference - elements in either but not both
a ^ b                        # {1, 2, 5, 6}
a.symmetric_difference(b)    # Same result

Modifying Sets

code.pyPython
fruits = {"apple", "banana"}

# Add single element
fruits.add("cherry")
print(fruits)  # {"apple", "banana", "cherry"}

# Add multiple elements
fruits.update(["date", "elderberry"])
fruits.update({"fig"}, ["grape"])  # Multiple iterables

# Remove element
fruits.remove("apple")   # Raises KeyError if not found
fruits.discard("mango")  # No error if not found
fruits.pop()             # Remove and return arbitrary element
fruits.clear()           # Remove all elements

Set Methods

MethodDescription
add(x)Add element x
remove(x)Remove x, raise KeyError if missing
discard(x)Remove x if present, no error
pop()Remove and return arbitrary element
clear()Remove all elements
copy()Return shallow copy
union(s)Return union with set s
intersection(s)Return intersection with s
difference(s)Return difference with s
issubset(s)Check if subset of s
issuperset(s)Check if superset of s

Membership and Comparisons

code.pyPython
fruits = {"apple", "banana", "cherry"}

# Membership - O(1) time complexity
"banana" in fruits      # True
"mango" not in fruits   # True

# Subset/Superset
a = {1, 2}
b = {1, 2, 3, 4}

a.issubset(b)     # True (a āŠ† b)
a <= b            # True (same as issubset)
a < b             # True (proper subset)

b.issuperset(a)   # True (b āŠ‡ a)
b >= a            # True
b > a             # True (proper superset)

# Disjoint (no common elements)
{1, 2}.isdisjoint({3, 4})  # True

Frozenset (Immutable Set)

code.pyPython
# Frozenset - immutable version of set
frozen = frozenset([1, 2, 3])
# frozen.add(4)  # AttributeError!

# Can be used as dictionary key
mapping = {
    frozenset([1, 2]): "pair",
    frozenset([3, 4, 5]): "triplet"
}

# Can be element of another set
set_of_sets = {frozenset([1, 2]), frozenset([3, 4])}

Practical Use Cases

code.pyPython
# Remove duplicates from list
items = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(items))

# Find common elements
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common = set(list1) & set(list2)  # {4, 5}

# Find unique elements
only_in_first = set(list1) - set(list2)  # {1, 2, 3}

# Fast lookup
valid_codes = {"A1", "B2", "C3"}
user_code = "B2"
if user_code in valid_codes:  # O(1) check
    print("Valid!")

# Count unique items
unique_count = len(set(items))

Interview Tip

When asked about sets:

  1. Unordered, unique elements only
  2. O(1) membership testing (vs O(n) for lists)
  3. Know set operations: | union, & intersection, - difference
  4. Use for deduplication and fast lookups
  5. Frozenset for immutable sets (can be dict keys)