Last updated

Python Sets

Definition: A set is a collection that holds only unique items — duplicates are automatically removed. It is written with curly braces { } (like a dictionary, but with single values, not pairs).

colors = {"red", "green", "blue", "red"}
print(colors)   # the duplicate "red" is dropped

Example 1 — sets are unordered

Items have no position, so you cannot use an index — but you can check membership very fast:

print("red" in colors)
print("yellow" in colors)

Example 2 — adding and removing

colors.add("yellow")
colors.remove("green")
print(colors)

Example 3 — removing duplicates from a list

A common trick: convert a list to a set to drop duplicates, then back to a list:

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

Example 4 — comparing two sets

a = {1, 2, 3}
b = {2, 3, 4}
print(a & b)   # {2, 3} — items in both
print(a | b)   # {1, 2, 3, 4} — items in either

💡 When to use: reach for a set whenever "no duplicates" or "is this present?" is the question.

Try it Yourself
Output

          
Ad · responsive