Last modified: Mar 17, 2026 By Alexander Williams

Python Sets Examples: Code for Unique Data

Python sets are powerful. They store unordered, unique items. This guide shows you how to use them.

We will explore many examples. You will learn to create and manipulate sets. Let's begin.

What is a Python Set?

A set is a built-in data type. It holds a collection of items. The items are unordered and unique.

No duplicate values are allowed. This makes sets perfect for deduplication. They are also very fast for membership tests.

For a deeper dive into their properties, see our Python Sets Guide: Unordered Unique Collections.

Creating a Set in Python

You can create a set using curly braces {} or the set() constructor.

Be careful. An empty {} creates a dictionary. Use set() for an empty set.


# Creating sets
my_set = {1, 2, 3, 4, 5}
print("Set with curly braces:", my_set)

another_set = set([10, 20, 30, 20, 10]) # Duplicates are removed
print("Set from a list:", another_set)

empty_set = set()
print("Empty set:", empty_set)

Set with curly braces: {1, 2, 3, 4, 5}
Set from a list: {10, 20, 30}
Empty set: set()

Adding and Removing Elements

Sets are mutable. You can add and remove items after creation.

Use add() for a single item. Use update() for multiple items.

Use remove() or discard() to delete items. discard() is safe. It doesn't raise an error if the item is missing.


# Modifying a set
fruits = {"apple", "banana"}
print("Original set:", fruits)

fruits.add("orange")
print("After add('orange'):", fruits)

fruits.update(["grape", "kiwi", "apple"]) # 'apple' is a duplicate
print("After update():", fruits)

fruits.remove("banana")
print("After remove('banana'):", fruits)

fruits.discard("mango") # No error, even though 'mango' isn't there
print("After discard('mango'):", fruits)

Original set: {'banana', 'apple'}
After add('orange'): {'banana', 'orange', 'apple'}
After update(): {'grape', 'orange', 'kiwi', 'apple'}
After remove('banana'): {'grape', 'orange', 'kiwi', 'apple'}
After discard('mango'): {'grape', 'orange', 'kiwi', 'apple'}

Set Operations: Union, Intersection, Difference

Sets support mathematical operations. These are very useful for comparing groups of data.

Union combines all unique items from both sets. Use the union() method or the | operator.

Intersection finds common items. Use intersection() or the & operator.

Difference finds items in the first set but not the second. Use difference() or the - operator.


# Set operations example
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}

union_set = set_a.union(set_b) # Or: set_a | set_b
print("Union of A and B:", union_set)

intersection_set = set_a.intersection(set_b) # Or: set_a & set_b
print("Intersection of A and B:", intersection_set)

difference_set = set_a.difference(set_b) # Or: set_a - set_b
print("Difference (A - B):", difference_set)

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

Union of A and B: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection of A and B: {4, 5}
Difference (A - B): {1, 2, 3}
Symmetric Difference: {1, 2, 3, 6, 7, 8}

Practical Example: Removing Duplicates

One of the most common uses for a set is to remove duplicates from a list. It is very efficient.

Simply convert the list to a set and back to a list. The order will be lost, but duplicates will be gone.


# Removing duplicates from a list
customer_ids = [101, 102, 101, 103, 104, 102, 105]
print("List with duplicates:", customer_ids)

unique_ids = list(set(customer_ids))
print("List without duplicates:", unique_ids)

List with duplicates: [101, 102, 101, 103, 104, 102, 105]
List without duplicates: [105, 101, 102, 103, 104]

Practical Example: Membership Testing

Checking if an item is in a set is extremely fast. It is much faster than checking in a list.

This is because sets use a hash table internally. Use this for large collections where you need to check membership often.


# Fast membership testing
valid_users = {"alice", "bob", "charlie", "diana", "eve"}
user_to_check = "bob"

if user_to_check in valid_users:
    print(f"Access granted for {user_to_check}.")
else:
    print(f"Access denied for {user_to_check}.")

# Checking for non-membership
if "mallory" not in valid_users:
    print("User 'mallory' is not in the valid set.")

Access granted for bob.
User 'mallory' is not in the valid set.

Frozenset: The Immutable Set

Python also provides a frozenset. It is just like a set, but it cannot be changed after creation.

This is useful when you need a set that can be used as a key in a dictionary or an element in another set.


# Using a frozenset
immutable_set = frozenset([5, 10, 15, 20])
print("Frozenset:", immutable_set)

# This would cause an error:
# immutable_set.add(25) # AttributeError: 'frozenset' object has no attribute 'add'

# Using frozenset as a dictionary key
config_map = {
    frozenset(["read", "write"]): "Admin",
    frozenset(["read"]): "Viewer"
}
print("Config for read/write:", config_map[frozenset(["read", "write"])])

Frozenset: frozenset({5, 10, 15, 20})
Config for read/write: Admin

Sets in a Real-World Context

Sets are not just academic. They solve real problems. For instance, when managing dependencies or environments in a project like Plone, understanding data structures is key.

If you're setting up a complex Python CMS, a solid grasp of types like sets is invaluable. You can learn more in our guide on Installing Plone 6: Complete Python Setup Guide.

Conclusion

Python sets are a versatile and efficient tool. They handle unique collections with ease.

You learned to create, modify, and operate on sets. We covered adding, removing, unions, and intersections.

You saw practical examples for deduplication and fast lookups. Remember the immutable frozenset for special cases.

Start using sets in your code today. They will make your programs cleaner and faster. They are perfect for any task involving unique items or membership checks.