⚡0 XP🔥0

Sets

Lesson 17 of 33 ⏱ 4 min read ✎ 3 exercises ❓ 6-question quiz ▶ Runs Python

Unordered collections of unique items - remove duplicates, fast membership tests, and set operations like union, intersection and difference.

What is a set?#

A set is a collection of unique items with no order. Sets use curly braces:

colors = {"red", "green", "blue"}
numbers = {1, 2, 3, 2, 1}      # duplicates removed -> {1, 2, 3}
empty = set()                  # NOT {} - that's an empty dict

Key properties:

  • No duplicates - each value appears once.
  • Unordered - no index, no slicing; printing order may vary.
  • Mutable - you can add/remove items, but the items themselves must be immutable (numbers, strings, tuples - not lists).
▶ Try it YourselfPython
Ctrl + Enter to run

Removing duplicates - the #1 use#

▶ Try it YourselfPython
Ctrl + Enter to run
Common Mistake

Converting to a set loses the original order. If order matters, use list(dict.fromkeys(items)) - it removes duplicates and keeps the first-seen order.

Fast membership testing#

Checking x in my_set is extremely fast, even with millions of items (lists check one by one):

blocked_users = {"spam1", "bot42", "fake99"}
if username in blocked_users:
    print("Access denied")

Adding and removing#

Method Purpose
add(x) add one item
update(iterable) add many items
remove(x) remove x - KeyError if missing
discard(x) remove x - no error if missing
pop() remove and return an arbitrary item
clear() empty the set
▶ Try it YourselfPython
Ctrl + Enter to run

Set operations (like maths Venn diagrams)#

Operation Operator Method Meaning
Union a | b a.union(b) all items from both
Intersection a & b a.intersection(b) items in both
Difference a - b a.difference(b) in a but not in b
Symmetric difference a ^ b a.symmetric_difference(b) in exactly one of them
▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

Set operations को Venn diagram की तरह सोचें - दो गोले जो थोड़े overlap करते हैं:

  • Union (|) - दोनों गोलों की सारी चीज़ें (कोई भी course करने वाले students)
  • Intersection (&) - बीच का common हिस्सा (दोनों courses करने वाले)
  • Difference (-) - सिर्फ पहले गोले का हिस्सा, common हटाकर (सिर्फ Python वाले)
  • Symmetric difference (^) - दोनों गोलों के अलग-अलग हिस्से, common हटाकर (जो सिर्फ एक course में हैं)

Subset and superset#

▶ Try it YourselfPython
Ctrl + Enter to run

frozenset - an immutable set#

frozenset can't be changed after creation, so it can be used as a dictionary key or inside another set:

weekend = frozenset({"Sat", "Sun"})

When to use a set#

Use a set when you need... Example
unique values unique customers, unique words
fast "is it there?" checks blocked IPs, valid coupon codes
comparisons between groups common friends, missing items

Summary#

  • Sets hold unique, unordered items: {1, 2, 3}; empty set is set().
  • set(list) removes duplicates; in checks are very fast.
  • add, update, remove, discard, pop, clear.
  • Union |, intersection &, difference -, symmetric difference ^.
  • No indexing - convert to a list (sorted(s)) if you need order.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Unique visitors

Print the number of unique visitor IDs in the list visits.

Expected output:
4
2

Common and exclusive skills

Using the two sets, print (each on its own line, as sorted lists):

  1. skills both candidates have
  2. all skills combined
  3. skills only Asha has
Expected output:
['python', 'sql']
['aws', 'excel', 'java', 'power bi', 'python', 'sql']
['excel', 'power bi']
3

Has duplicates?

Read space-separated words on one line. Print True if any word repeats, else False.

Test input:
red blue green blue yellow
Expected output:
True

Quick Quiz

Q1.

What is len({1, 2, 2, 3, 3, 3})?

Q2.

How do you create an empty set?

Q3.

What is {1, 2, 3} & {2, 3, 4}?

Q4.

What is {1, 2, 3} - {2, 3, 4}?

Q5.

Why does my_set[0] give an error?

Q6.

Which removes an item without raising an error if it's missing?