Course topics

By WebNest Studio

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.

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().

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 the examples

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