agyanadda@gmail.com

Python Sets

Python Data Structures 1 min read Updated Dec 4, 2026 Topic 14 of 32

A set is an unordered collection of unique items: tags = {"python", "web"}.

Create

  • {1, 2, 3}
  • set([1, 1, 2]) → {1, 2} — duplicates removed
  • Empty set: set() — {} creates an empty dictionary

Add and remove

add(x), update([...]), remove(x) (error if missing), discard(x) (no error), pop(), clear().

Set operations

Operation Operator Meaning
Union a | b in either
Intersection a & b in both
Difference a - b in a, not b
Symmetric difference a ^ b in one, not both

Also issubset(), issuperset(), isdisjoint().

Why sets?

  • Remove duplicates quickly
  • Very fast in checks, even with millions of items
  • Compare groups (common friends, missing items)

Sets have no index — you cannot do s[0]. Items must be immutable (numbers, strings, tuples).

Example

Example — Course enrolments Python
python_batch = {"Asha", "Ravi", "Neha", "Amit"}
web_batch = {"Ravi", "Zoya", "Amit"}

print("Both courses:", python_batch & web_batch)
print("Any course:", python_batch | web_batch)
print("Only Python:", python_batch - web_batch)
print("Exactly one:", python_batch ^ web_batch)

emails = ["a@x.com", "b@x.com", "a@x.com", "c@x.com", "b@x.com"]
unique = set(emails)
print(len(emails), "->", len(unique))

blocked = {"spam@x.com"}
print("spam@x.com" in blocked)

print(type({}), type(set()))

Shows students in both courses {'Ravi', 'Amit'}, the union, Python-only students, and those in exactly one course (set order may vary). Then 5 -> 3, True, and <class 'dict'> <class 'set'>.

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does {} create?

Exercise 2 True / False

A set keeps only unique values.

Exercise 3 Fill in the Blank

Items in both sets a and b: a ___ b

Frequently Asked Questions

Yes: list(dict.fromkeys(items)) removes duplicates and keeps the first-seen order, because dictionaries preserve insertion order.