Python ยท Chapter 17 of 45

Python Sets

A set is an UNORDERED collection of UNIQUE items. Duplicates are automatically removed.

Create with `{1, 2, 3}` or `set([1,2,3])`. Note: `{}` is an empty DICT, not a set.

Set operations

Sets support union `|`, intersection `&`, difference `-`, and symmetric difference `^` โ€” exactly like math.

Common uses

De-duplicating a list, fast membership checks, and computing intersections between groups.

Example 1 (python)
nums = [1, 2, 2, 3, 3, 3]
unique = set(nums)
print(unique)
Output
{1, 2, 3}

set() removes duplicates from a list.

Example 2 (python)
a = {1, 2, 3}
b = {2, 3, 4}
print(a & b)
print(a | b)
Output
{2, 3}
{1, 2, 3, 4}

& is intersection, | is union.

Key points

  • Unordered, unique items.
  • `{...}` for non-empty, `set()` for empty.
  • Supports set operations: `|`, `&`, `-`, `^`.
  • Membership check `x in s` is very fast.
๐Ÿ’ก Note: `{}` creates an empty DICT. For an empty set, use `set()`.

๐Ÿ“ Quick Quiz

1. Sets allow duplicates?

2. What is `{}`?

3. Which operator gives the intersection?