Python Tutorial · Data Structures · Lesson 17 of 42

Python Sets

Unordered collections of unique items and fast membership tests.

Creating sets

A set stores unique items with no order. Duplicates are removed automatically.

Example 1Try it yourself
tags = {"python", "web", "python", "api"}
print(len(tags))
tags.add("ml")
tags.discard("web")
print(sorted(tags))
print("api" in tags)

Output

3
['api', 'ml', 'python']
True

{} creates an empty dict, not a set — use set() for an empty set.

Set operations

Example 2Try it yourself
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b)   # union
print(a & b)   # intersection
print(a - b)   # difference
print(a ^ b)   # in one but not both

Output

{1, 2, 3, 4, 5}
{3, 4}
{1, 2}
{1, 2, 5}

Why sets are fast

Checking item in some_set takes about the same time no matter how big the set is (it's a hash lookup), while item in some_list checks items one by one. Use sets for de-duplication and membership tests.

Example 3Try it yourself
emails = ["[email protected]", "[email protected]", "[email protected]"]
unique = list(dict.fromkeys(emails))  # de-duplicate, keep order
print(unique)
seen = set()
for e in emails:
    if e in seen:
        print("duplicate:", e)
    seen.add(e)

Test yourself

What is len({1, 1, 2, 2, 3})?

  1. 5
  2. 3
  3. 2
  4. 1
Show answer

Answer: 3

Practice next