Syntax
{item1, item2, item3}Examples
Creating Sets
Building a set and observing automatic deduplication.
numbers = {1, 2, 2, 3, 3, 3}
print(numbers) # {1, 2, 3} - duplicates removed automatically
empty = set() # NOT {} - that creates an empty dict instead
print(type(empty))Set Operations
Using union, intersection, and difference to compare sets.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union: {1, 2, 3, 4, 5, 6}
print(a & b) # intersection: {3, 4}
print(a - b) # difference: {1, 2}
print(a ^ b) # symmetric difference: {1, 2, 5, 6}Adding and Removing Items
Modifying a set after creation.
tags = {"python", "web"}
tags.add("backend")
print(tags)
tags.discard("web") # no error if 'web' isn't present
print(tags)
print("python" in tags) # fast membership checkRemoving Duplicates from a List
A very common practical use of sets: deduplicating a list while (optionally) preserving order.
names = ["John", "Zain", "John", "Jamal", "Zain"]
unique_names = list(set(names))
print(unique_names) # order not guaranteed
# Preserve original order while deduplicating
seen = set()
ordered_unique = []
for name in names:
if name not in seen:
seen.add(name)
ordered_unique.append(name)
print(ordered_unique) # ['John', 'Zain', 'Jamal']Best practices
- Use set() to create an empty set - {} creates an empty dictionary instead, a common source of confusion
- Reach for a set when you need fast membership testing (x in my_set) on a large collection - it is much faster than checking a list
- Use sets to deduplicate data, but remember they do not preserve insertion order in general (use a dict or an ordered loop if order matters)
- Only hashable items (numbers, strings, tuples) can go in a set - lists and dictionaries cannot be set members
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference