A Python set is an unordered collection of unique elements. Unlike a list, a set automatically drops duplicates and does not preserve insertion order, which makes it the right tool whenever you only care about "is this value present" or "what's different between these two collections."

Sets are mutable, but every element inside a set must itself be immutable (hashable) — so a set can hold numbers, strings, and tuples, but not lists or dictionaries. This restriction is what lets Python check membership in a set almost instantly, no matter how large it grows.

Creating a Set

fruits = {"apple", "banana", "apple", "cherry"}
print(fruits)

# An empty set must use set(), not {} (that creates a dict)
empty = set()
print(type(empty))

Output:

{'banana', 'apple', 'cherry'}
<class 'set'>

Notice the duplicate "apple" was silently dropped, and the printed order doesn't match the order it was typed in — sets don't guarantee any particular order.

Set Operations: Union, Intersection, Difference

This is where sets really earn their place in your toolkit — they implement the classic mathematical set operations directly as operators or methods.

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)   # union: all elements in either set
print(a & b)   # intersection: elements in both sets
print(a - b)   # difference: in a but not in b
print(a ^ b)   # symmetric difference: in a or b, but not both

Output:

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

You can also use .add(value) to insert a single element, .remove(value) to delete one (raises an error if missing), .discard(value) to delete one safely, and in to check membership — all of these run in roughly constant time, which is the main reason to reach for a set.

When to Use a Set Instead of a List

Reach for a set when you need fast membership checks or you need to remove duplicates from a collection — for example, list(set(my_list)) is a quick (though order-losing) way to deduplicate a list. If you need to preserve order, or you need duplicate values, or the elements aren't hashable, stick with a list instead. For counting how often things occur rather than just whether they occur, a dictionary (covered in our dictionaries tutorial) or collections.Counter is a better fit, as shown in our most frequent element program.