stackademic

The leading education platform for anyone with an interest in software development.

Python Sets

Unordered collections of unique elements for membership and set math

Overview

Sets store unique, hashable items with no guaranteed order. They excel at deduplication, membership tests, and set operations like union and intersection.

Syntax / Usage

# Create
tags = {"python", "web", "api"}
from_list = set([1, 2, 2, 3])  # {1, 2, 3}
empty = set()  # not {} which is a dict

# Add and remove
tags.add("devops")
tags.discard("web")  # no error if missing
tags.remove("api")   # KeyError if missing

# Membership (fast)
"python" in tags  # True

# Set operations
a = {1, 2, 3}
b = {3, 4, 5}
a | b   # union: {1, 2, 3, 4, 5}
a & b   # intersection: {3}
a - b   # difference: {1, 2}

Examples

Find users in both groups:

group_a = {"alice", "bob", "carol"}
group_b = {"bob", "dave", "eve"}
both = group_a & group_b  # {"bob"}

Remove duplicates while preserving rough order (use dict keys in 3.7+):

items = ["a", "b", "a", "c", "b"]
unique = list(dict.fromkeys(items))  # ["a", "b", "c"]

Common Mistakes

  • Using {} for an empty set—it creates an empty dict
  • Adding unhashable items like lists to a set
  • Expecting sets to maintain insertion order in older Python versions
  • Using sets when you need indexed access—use a list instead

See Also

python-dictionaries python-tuples python-list-comprehension