Last modified: Mar 17, 2026 By Alexander Williams

Python Sets Guide: Unordered Unique Collections

Python offers many data structures. A set is one of the most useful. It is a built-in collection type.

This guide explains Python sets. You will learn their core properties and common operations.

Defining a Python Set

A set is an unordered collection. It contains unique, immutable elements. Duplicate items are not allowed.

Sets are mutable. You can add and remove items after creation. But the items themselves must be immutable.

You create a set with curly braces {} or the set() constructor. Let's see an example.


# Creating a set with curly braces
my_set = {1, 2, 3, 4, 5}
print(my_set)
# Creating a set from a list using set()
another_set = set([5, 6, 7, 8])
print(another_set)
    

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

Notice the output order. The set another_set prints as {8, 5, 6, 7}. This shows the unordered nature of sets.

An empty set must be created with set(). Using {} creates an empty dictionary.

Key Characteristics of Sets

Understanding set properties is crucial. They define when and how to use this data type.

Unordered Collection

Sets have no index positions. Items are not stored in the order they are added. You cannot access elements by index like a list.

This is because sets use a hash table internally. Order is not guaranteed.

Unique Elements

Every element in a set must be unique. If you try to add a duplicate, it is silently ignored.

This makes sets perfect for removing duplicates from a sequence.


# Sets automatically remove duplicates
duplicate_list = [1, 2, 2, 3, 3, 3, 4]
unique_set = set(duplicate_list)
print(unique_set)
    

{1, 2, 3, 4}
    

Mutable but Elements are Immutable

The set itself can change. You can add and remove items. However, the items you put in a set must be immutable.

You can include integers, floats, strings, and tuples. You cannot include lists, dictionaries, or other sets.

This restriction is due to the hashing mechanism. It requires stable values.

Common Set Operations and Methods

Python provides many operations for sets. They are similar to mathematical set operations.

Adding and Removing Elements

Use add() to insert a single item. Use update() to add multiple items from an iterable.

Use remove() or discard() to delete an item. remove() raises an error if the item is missing. discard() does not.


fruits = {"apple", "banana"}
fruits.add("orange")
print(fruits)
fruits.update(["grape", "kiwi"])
print(fruits)
fruits.discard("banana")
print(fruits)
# fruits.remove("mango") # This would raise a KeyError
    

{'banana', 'orange', 'apple'}
{'banana', 'orange', 'apple', 'kiwi', 'grape'}
{'orange', 'apple', 'kiwi', 'grape'}
    

Mathematical Set Operations

Sets support union, intersection, difference, and symmetric difference. These are powerful for data comparison.

Union combines elements from both sets. Intersection finds common elements. Difference finds items in one set but not the other.


set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

# Union: all items in either set
print("Union:", set_a | set_b)  # or set_a.union(set_b)

# Intersection: common items
print("Intersection:", set_a & set_b)  # or set_a.intersection(set_b)

# Difference: in A but not in B
print("Difference (A - B):", set_a - set_b)  # or set_a.difference(set_b)

# Symmetric Difference: in A or B but not both
print("Symmetric Diff:", set_a ^ set_b)  # or set_a.symmetric_difference(set_b)
    

Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference (A - B): {1, 2}
Symmetric Diff: {1, 2, 5, 6}
    

Membership Testing

Checking if an item is in a set is very fast. This is a key strength of sets. It uses the underlying hash table.

It is much faster than checking membership in a list.


my_set = {10, 20, 30, 40, 50}
# Fast membership test
if 30 in my_set:
    print("30 is in the set")
    

30 is in the set
    

Frozenset: The Immutable Set

Python also provides frozenset. It is an immutable version of a set. You cannot change it after creation.

Because it is immutable, a frozenset can be used as a dictionary key or an element in another set.


# Creating a frozenset
immutable_set = frozenset([1, 2, 3])
print(immutable_set)
# immutable_set.add(4) # This would raise an AttributeError
    

frozenset({1, 2, 3})
    

When to Use a Python Set

Sets are ideal for specific tasks. Use them when you need to enforce uniqueness or perform fast lookups.

They are perfect for removing duplicates from a list. Simply convert the list to a set and back.

Use sets for membership testing. The in keyword works in constant time on average.

Mathematical set operations are another great use case. They simplify comparing groups of data.

Before working with sets, ensure you have a proper Python environment. For a robust setup, especially for web development, you might follow a guide like Installing Plone 6: Complete Python Setup Guide.

Conclusion

A Python set is a powerful, unordered collection of unique items. Its main strengths are enforcing uniqueness and providing fast membership tests.

Remember its key traits: unordered, unique, and containing only immutable elements. Use methods like add(), remove(), and union() to manipulate them.

Sets are a fundamental tool. They solve problems involving duplicates and set logic efficiently. Add them to your Python toolkit today.