SkillByAIOpen interactive version →

Lesson 12 / 49

Sets

Remove duplicates and test membership quickly with sets, and combine them with union, intersection and difference.

Unique & fast lookups

A set automatically drops duplicates and checks membership in near-constant time.

tags = {"python", "web", "python"}
print(tags)          # {'python', 'web'}
print("web" in tags) # True

Set operations

Sets support math operations: union, intersection, difference — handy for comparing groups.

a = {1, 2, 3}
b = {2, 3, 4}
print(a | b)   # union {1,2,3,4}
print(a & b)   # intersection {2,3}
print(a - b)   # difference {1}