Python Sets

Unordered collections of unique items.

✍️ 3 exercises + code challenge in this lesson

A set stores unique items with no order: tags = {"python", "web"}

  • Duplicates are removed automatically.
  • Add with add() or update(); remove with remove() or discard().
  • Set maths: | union, & intersection, - difference, ^ symmetric difference.
An empty set is created with set(). {} creates an empty dictionary.

Key Takeaways: Python Sets

Mastering Python Sets helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Python Sets Code Example

Python
a = {"python", "sql", "html"}
b = {"html", "css", "javascript"}

print("Union:", a | b)
print("Both:", a & b)
print("Only in a:", a - b)

a.add("python")   # duplicate: no change
a.add("git")
print(a)
print(len({1, 1, 2, 2, 3}))
Free sign-in required · Google login available

Python Sets Practice Exercises

Check what you learned in “Python Sets”.

/ 3 solved
Fill in the blank

Create an empty set.

tags = 
✓ Correct! Not quite. Try again.
Multiple choice

What happens when you add a duplicate to a set?

✓ Correct! Not quite. Try again.
Code challenge

Print the items both sets have in common, sorted as a list.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services