PYTHON • Intermediate

Python Sets

A set is an unordered collection of unique items. Sets do not allow duplicates and do not maintain any order. They're perfect for removing duplicates, membership testing, and mathematical operations like union and intersection.

Creating a Set

# Using curly braces
fruits = {"apple", "banana", "mango"}

# Using set() constructor
numbers = set([1, 2, 3, 4, 5])

# Empty set — cannot use {} (that's a dict)
empty = set()

# From string (each character becomes an item)
chars = set("hello")
print(chars)   # {'h', 'e', 'l', 'o'} — note: only unique
⚠ Important

{} creates an empty dictionary, not a set. To create an empty set, use set().

Sets Remove Duplicates Automatically

nums = [1, 2, 2, 3, 3, 3, 4]
unique = set(nums)
print(unique)   # {1, 2, 3, 4}

Sets are Unordered

You cannot access items by index. Sets do not support indexing or slicing.

fruits = {"apple", "banana", "mango"}

# print(fruits[0])   # ❌ TypeError
# print(fruits[1:])  # ❌ TypeError

# But you can loop through
for fruit in fruits:
    print(fruit)

Adding and Removing Items

fruits = {"apple", "banana"}

# Add one item
fruits.add("mango")
print(fruits)   # {'apple', 'banana', 'mango'}

# Add multiple
fruits.update(["grape", "kiwi"])

# Remove item (raises error if not found)
fruits.remove("banana")

# Remove item (safe — no error if missing)
fruits.discard("papaya")

# Remove and return random item
item = fruits.pop()

# Clear all
fruits.clear()

print(fruits)

Set Operations

The real power of sets lies in mathematical operations.

Union (|)

All unique items from both sets.

a = {1, 2, 3}
b = {3, 4, 5}

print(a | b)              # {1, 2, 3, 4, 5}
print(a.union(b))         # same

Intersection (&)

Items common to both sets.

print(a & b)              # {3}
print(a.intersection(b))  # {3}

Difference (-)

Items in first set but not in second.

print(a - b)              # {1, 2}
print(a.difference(b))    # {1, 2}

Symmetric Difference (^)

Items in either set but not in both.

print(a ^ b)                       # {1, 2, 4, 5}
print(a.symmetric_difference(b))   # {1, 2, 4, 5}

Membership Testing

Sets are extremely fast at checking if an item exists — much faster than lists.

fruits = {"apple", "banana", "mango"}

print("apple" in fruits)     # True
print("grape" in fruits)     # False
print("kiwi" not in fruits)  # True

Set Methods Summary

  • add() — add one item
  • update() — add multiple items
  • remove() — remove item (raises error if missing)
  • discard() — remove item (safe)
  • pop() — remove random item
  • clear() — remove all items
  • union() — combine sets
  • intersection() — common items
  • difference() — items in first, not second
  • issubset() — check if all items in another set
  • issuperset() — check if contains all items of another set

Frozen Set — Immutable Set

A frozenset is like a set but immutable. Can be used as dictionary keys.

fs = frozenset([1, 2, 3, 4])

# fs.add(5)   # ❌ AttributeError

# All read operations work
print(2 in fs)           # True
print(fs.union({5, 6}))  # frozenset({1, 2, 3, 4, 5, 6})
💡 Academy Tip

Use sets when you need to remove duplicates quickly or perform mathematical operations. Use lists when order matters and duplicates are allowed.

Real-World Use Case

# Find unique visitors
visitors_today = {"Ankit", "Priya", "Rahul", "Ankit"}
visitors_yesterday = {"Priya", "Sneha"}

# Unique visitors today
print("Today:", visitors_today)   # {'Ankit', 'Priya', 'Rahul'}

# Repeat visitors
print("Repeats:", visitors_today & visitors_yesterday)   # {'Priya'}

# New visitors today
print("New:", visitors_today - visitors_yesterday)         # {'Ankit', 'Rahul'}
📝 Try Yourself

Create two sets of your favorite fruits and your friend's favorite fruits. Print: all fruits (union), common fruits (intersection), fruits only you like (difference), and fruits only your friend likes (reverse difference).

Quick Revision

  • Sets are unordered, mutable, unique items only.
  • Created with {} or set().
  • {} is a dict — use set() for empty set.
  • No indexing, no slicing.
  • Operations: union |, intersection &, difference -, symmetric difference ^.
  • Fast membership testing: in, not in.
  • frozenset() is immutable.

Interview Questions

Q: Difference between a set and a list?

A: Sets are unordered and store unique items only — duplicates are removed automatically. Lists are ordered, allow duplicates, and support indexing/slicing. Sets are faster for membership tests; lists are faster for indexed access.

Q: What is a frozenset and where is it used?

A: A frozenset is an immutable set. It's used when you need a set that cannot be changed — for example, as a dictionary key or as a value in another set.

Q: How do you remove duplicates from a list?

A: list(set(my_list)) removes duplicates but loses order. To preserve order, use list(dict.fromkeys(my_list)).

Q: Explain union, intersection, and difference of sets.

A: Union (|) = all items from both sets. Intersection (&) = items common to both. Difference (-) = items in first set but not second.

Want to Master Python?

Join our Python course in Varanasi — practical classes and career support at our Sarnath centre.

Ask on WhatsApp
Chat with us