Course topics

By WebNest Studio Engineering Team

Python Tutorial

Python Sets and Set Methods

A set is an unordered collection of unique, hashable items. Sets remove duplicates automatically, test membership in constant time, and support mathematical operations like union, intersection and difference — perfect for "which students attended both classes?" or "which tags are new?".

This lesson covers creating sets, every set method, set operators, frozensets, and when sets outperform lists.

Why it matters

Questions such as "which customers bought both products?" or "which ids are in this file but not in that one?" are set operations. Writing them with sets takes one line and runs quickly; writing them with nested loops over lists is longer and becomes slow as the data grows.

Creating Sets

Use braces with values {1, 2, 3} or set(iterable). {} is an empty dict, so an empty set is set(). Items must be hashable — numbers, strings, tuples are fine; lists and dicts are not. Sets have no order and no indexing.

Adding and Removing

add(x) adds one item; update(iterable) adds many. remove(x) raises KeyError if missing, discard(x) does not; pop() removes and returns an arbitrary item; clear() empties the set; copy() makes a shallow copy.

Set Algebra

Each operation has a method and an operator: union (|), intersection (&), difference (-), symmetric_difference (^). The _update versions (intersection_update, difference_update, symmetric_difference_update, and |=, &=...) modify the set in place. issubset (<=), issuperset (>=) and isdisjoint compare sets.

frozenset and Performance

A frozenset is an immutable, hashable set that can be a dict key or an element of another set. Membership tests (x in s) on sets are O(1) on average versus O(n) for lists — for large collections this is dramatically faster.

Examples

Creating sets and removing duplicates

Python
tags = {"python", "web", "python", "api"}
print(sorted(tags), len(tags))
emails = ["a@x.in", "b@x.in", "a@x.in"]
print(sorted(set(emails)))
print(type({}), type(set()))
print(sorted(set("mississippi")))
Output
['api', 'python', 'web'] 3
['a@x.in', 'b@x.in']
<class 'dict'> <class 'set'>
['i', 'm', 'p', 's']

Adding and removing items

Python
s = {1, 2, 3}
s.add(4)
s.update([5, 6], {7})
print(sorted(s))
s.remove(7)
s.discard(100)             # no error
print(sorted(s))
try:
    s.remove(100)
except KeyError as e:
    print("KeyError:", e)
backup = s.copy()
item = s.pop()
s.clear()
print(len(s), len(backup), item in backup)
Output
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6]
KeyError: 100
0 6 True

Union, intersection, difference and symmetric difference

Python
monday = {"Asha", "Ravi", "Meera", "Kiran"}
tuesday = {"Ravi", "Kiran", "John"}

print("either day :", sorted(monday | tuesday))
print("both days  :", sorted(monday & tuesday))
print("only Monday:", sorted(monday - tuesday))
print("one day    :", sorted(monday ^ tuesday))
print(sorted(monday.union(tuesday, {"Zoya"})))

team = {"Ravi", "Kiran"}
print(team <= monday, monday >= team, team.isdisjoint({"John"}))

pending = {"a", "b", "c"}
pending.difference_update({"b"})
pending.intersection_update({"a", "c", "z"})
pending.symmetric_difference_update({"c", "d"})
print(sorted(pending))
Output
either day : ['Asha', 'John', 'Kiran', 'Meera', 'Ravi']
both days  : ['Kiran', 'Ravi']
only Monday: ['Asha', 'Meera']
one day    : ['Asha', 'John', 'Meera']
['Asha', 'John', 'Kiran', 'Meera', 'Ravi', 'Zoya']
True True True
['a', 'd']

frozenset and fast membership

Python
import time

vowels = frozenset("aeiou")
print("e" in vowels, {vowels: "vowel set"}[vowels])

big_list = list(range(1_000_000))
big_set = set(big_list)
start = time.perf_counter(); 999_999 in big_list; t_list = time.perf_counter() - start
start = time.perf_counter(); 999_999 in big_set; t_set = time.perf_counter() - start
print("set lookup faster:", t_set < t_list)
Output
True vowel set
set lookup faster: True

Common Mistakes

  • Writing {} for an empty set.
  • Expecting sets to keep insertion order or support indexing.
  • Adding lists to a set (TypeError: unhashable type) — convert to tuples.
  • Using remove() for items that may be missing instead of discard().

Exercise

Two courses have the students shown below. Print the students who take both courses, then the students who take only Python, then the total number of different students. Sort the names before printing.

Expected output: ['Ravi'], ['Asha', 'Zoya'], 4 (one per line)

Python · starter code
python_course = {"Asha", "Ravi", "Zoya"}
java_course = {"Ravi", "Meera"}

# TODO: print the sorted names of students in both courses
# TODO: print the sorted names of students only in the Python course
# TODO: print how many different students there are in total
Show hints
  • a & b is the intersection, a - b the difference and a | b the union.
  • A set has no order, so pass it to sorted() before printing.
Show solution
Python · solution
python_course = {"Asha", "Ravi", "Zoya"}
java_course = {"Ravi", "Meera"}

print(sorted(python_course & java_course))
print(sorted(python_course - java_course))
print(len(python_course | java_course))

Quick quiz

1. How is an empty set created?

  • A. {}
  • B. set()
  • C. []
  • D. ()
Show answer

B. {} creates an empty dictionary.

2. What is the difference between remove(x) and discard(x) when x is not in the set?

  • A. There is none
  • B. remove raises KeyError; discard does nothing
  • C. discard raises KeyError; remove does nothing
  • D. Both raise an error
Show answer

B. Use discard when it does not matter whether the item was present.

3. Can a list be an element of a set?

  • A. Yes
  • B. Only inside a frozenset
  • C. Only an empty list
  • D. No; set elements must be hashable, and a list is not
Show answer

D. Use a tuple instead, which is hashable when its elements are.

Interview questions

How is a set implemented, and what does that mean for its performance?

Show answer

A set is a hash table. The hash of each element decides where it is stored, so adding an element, removing one and testing membership all take roughly constant time on average, however large the set is. The consequences are that elements must be hashable and that a set has no defined order.

What is a frozenset?

Show answer

A frozenset is an immutable set. It supports the same reading operations and set algebra as a set, but has no methods that change it. Because it cannot change it is hashable, so it can be used as a dictionary key or as an element of another set.

Key Points to Remember

  • Sets hold unique hashable items with no order.
  • add/update add; remove (KeyError), discard (safe), pop, clear remove.
  • union |, intersection &, difference -, symmetric_difference ^, plus _update variants.
  • issubset, issuperset and isdisjoint compare sets.
  • frozenset is immutable and hashable; set membership is O(1).

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering