Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Sets in Python: A Practical Beginner Guide

2 min read .
Sets in Python: A Practical Beginner Guide

A Python set is a mutable collection of unique, hashable elements. Sets are especially useful for membership tests, deduplication, and mathematical set operations such as union and intersection.

Create a Set

Use braces for a non-empty set:

numbers = {1, 2, 3, 4, 5}

Duplicates are removed automatically:

numbers = {1, 1, 2, 2, 3}
print(numbers)

To create an empty set, use set():

empty = set()

{} creates an empty dictionary, not an empty set.

Create a Set from Another Iterable

names = set(["Alice", "Bob", "Alice"])
print(names)

This is a common way to remove duplicates when preserving order is not required.

If order matters, use another technique such as:

unique_names = list(dict.fromkeys(["Alice", "Bob", "Alice"]))

Add and Remove Elements

Add one item:

numbers.add(6)

Add several items:

numbers.update([7, 8, 9])

Remove an item and raise KeyError if it is missing:

numbers.remove(3)

Remove an item without failing when it is absent:

numbers.discard(3)

pop() removes and returns an arbitrary element:

value = numbers.pop()

Do not rely on which element pop() chooses.

Membership Tests

allowed_roles = {"admin", "editor", "viewer"}

if "admin" in allowed_roles:
    print("Allowed")

Set membership is typically efficient because sets are hash-based collections.

Union

left = {1, 2, 3}
right = {3, 4, 5}

print(left | right)
print(left.union(right))

Both produce all unique elements from both sets.

Intersection

print(left & right)
print(left.intersection(right))

This returns values present in both sets.

Difference

print(left - right)  # {1, 2}

Difference is directional: left - right is not necessarily the same as right - left.

Symmetric Difference

print(left ^ right)

This returns elements present in exactly one of the sets.

Subsets and Supersets

small = {1, 2}
large = {1, 2, 3}

print(small <= large)  # subset
print(large >= small)  # superset
print(small < large)   # proper subset

Set Comprehensions

even_squares = {number * number for number in range(10) if number % 2 == 0}

Like dictionary and list comprehensions, this provides a concise way to build a collection from an iterable.

Elements Must Be Hashable

A set can contain immutable hashable values such as strings, integers, and suitable tuples:

points = {(0, 0), (10, 20)}

It cannot directly contain mutable lists or dictionaries:

# invalid = {[1, 2], [3, 4]}

For an immutable set value, use frozenset:

permissions = frozenset({"read", "write"})

A frozenset can itself be used as a dictionary key or stored inside another set when its elements are hashable.

Ordering

Sets should be treated as unordered collections. Their displayed or iteration order is not a stable semantic contract to build application logic around. If deterministic ordering is required, sort the values explicitly:

for value in sorted(numbers):
    print(value)

Conclusion

Use sets when uniqueness and membership matter more than position or order. They provide concise union, intersection, difference, and subset operations, but their elements must be hashable and their iteration order should not be relied upon.

Related Posts

chevron-up