Python - Sets

Overview

Estimated time: 15–25 minutes

Use sets for fast membership tests and deduplication. Learn basic operations and typical patterns.

Learning Objectives

  • Create sets and perform union, intersection, difference, symmetric difference.
  • Use set comprehensions.
  • Understand hashability and why elements must be immutable.

Prerequisites

Basics and operations

a = {1, 2, 3}
b = {3, 4}
print(2 in a)
print(a | b, a & b, a - b, a ^ b)

Deduplication

data = [1, 2, 2, 3]
print(list(set(data)))

Common Pitfalls

  • Lists are unhashable; use tuples for compound members: {(x, y)}.
  • Set literals require braces; empty set is set() not {} (that’s an empty dict).

Checks for Understanding

  1. How do you compute the intersection of two sets?
  2. Why can’t you put a list into a set?
Show answers
  1. a & b or a.intersection(b)
  2. Lists are mutable and unhashable; set elements must be hashable.

Exercises

  1. Given two lists, print common unique elements using sets.
  2. Use a set to check if a string has duplicate characters.