Part 4 · Collections — chapter 3 of 6 · chapter 19 of 50 · 7 min read

Python Sets Explained

A Python set is a built-in collection type that stores unique values only. It is useful when you want to remove duplicates, check whether a value exists, or compare groups of items.

Sets are different from lists and tuples because they are unordered. That means items do not have a fixed position, and you cannot access them with an index like my_set[0].

Below you will see how to create sets, add and remove items, and use them to compare groups of values.

Quick example #

numbers = {1, 2, 3}
numbers.add(4)

print(numbers)
print(2 in numbers)

What this does:

  • Creates a set with the values 1, 2, and 3
  • Adds 4 with add()
  • Checks whether 2 is in the set

Possible output:

{1, 2, 3, 4}
True

Use a set when you want unique values and fast membership checks.

What a Python set is #

A set in Python:

  • Is a built-in collection type
  • Stores unique values only
  • Removes duplicate values automatically
  • Is unordered
  • Uses curly braces, like dictionaries, but contains only values

Example:

colors = {"red", "blue", "red", "green"}
print(colors)

Possible output:

{'blue', 'green', 'red'}

Even though "red" was written twice, it appears only once in the set.

Why beginners use sets #

Beginners often use sets for practical tasks such as:

  • Removing duplicate items from data
  • Checking if a value exists quickly
  • Comparing groups of values
  • Finding shared or different items between collections

For example, if you have a list with repeated values, a set can help remove duplicates:

numbers = [1, 2, 2, 3, 3, 3]
unique_numbers = set(numbers)

print(unique_numbers)

Output:

{1, 2, 3}

If your goal is specifically to remove duplicates from a list, see how to remove duplicates from a list in Python.

How to create a set #

You can create a set in a few simple ways.

Create a set with curly braces #

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

Create an empty set #

Use set() for an empty set:

empty_set = set()
print(type(empty_set))

Output:

<class 'set'>

Do not use {} if you want an empty set.

empty_value = {}
print(type(empty_value))

Output:

<class 'dict'>

{} creates an empty dictionary, not a set.

For more detail, see creating a set in Python.

Build a set from another collection #

You can create a set from a list, tuple, or string with set().

letters = set(["a", "b", "a", "c"])
print(letters)

Output:

{'a', 'b', 'c'}

Important set behavior #

There are a few rules beginners should understand early.

Sets are unordered #

A set does not keep items in a fixed position.

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

The display order may not match the order you wrote.

You cannot access items by index #

This will not work:

fruits = {"apple", "banana", "orange"}
# print(fruits[0])

Sets do not support indexing because they are unordered.

Set output order may look different #

If you print a set, the order may look different across runs. This is normal.

Items must be hashable #

A set can store values like:

  • Integers
  • Strings
  • Tuples

But mutable values like lists and dictionaries cannot be stored in a set.

This works:

items = {(1, 2), (3, 4)}
print(items)

This does not work:

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

A list is mutable, so Python raises an error if you try to put it in a set.

If you want a shorter definition, see what is a set in Python.

Basic set operations beginners should know #

These are the main methods beginners use first.

add() adds one item #

numbers = {1, 2, 3}
numbers.add(4)

print(numbers)

Use Python set add() if you want to learn this method in more detail.

remove() removes an item #

numbers = {1, 2, 3}
numbers.remove(2)

print(numbers)

Output:

{1, 3}

But remove() raises an error if the item is missing:

numbers = {1, 2, 3}
# numbers.remove(5)

See Python set remove() for examples and error behavior.

discard() removes an item without an error #

numbers = {1, 2, 3}
numbers.discard(5)

print(numbers)

Nothing goes wrong here, even though 5 is not in the set.

See Python set discard() for the difference between discard() and remove().

pop() removes and returns a random item #

numbers = {1, 2, 3}
removed_item = numbers.pop()

print(removed_item)
print(numbers)

Because sets are unordered, you should not expect a specific item to be removed.

clear() removes all items #

numbers = {1, 2, 3}
numbers.clear()

print(numbers)

Output:

set()

Common set operations for comparing values #

Sets are very useful when you want to compare values between two groups.

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

union() combines items from both sets #

print(a.union(b))

Output:

{1, 2, 3, 4, 5}
ab12345
a.union(b) shades both circles: all unique values from a and b.

See Python set union().

intersection() finds shared items #

print(a.intersection(b))

Output:

{3}

See Python set intersection().

difference() finds items only in the first set #

print(a.difference(b))

Output:

{1, 2}

symmetric_difference() finds items in either set but not both #

print(a.symmetric_difference(b))

Output:

{1, 2, 4, 5}

When to use a set instead of a list #

Use a set when:

  • Duplicates should not exist
  • Order does not matter
  • You want fast membership checks like value in my_set

Use a list when:

  • Item order matters
  • You need indexing
  • You need slicing

Example:

names_list = ["Ana", "Ben", "Ana"]
names_set = {"Ana", "Ben"}

print("Ana" in names_list)
print("Ana" in names_set)

Both can check membership, but a set is designed for this kind of lookup.

If you want a bigger comparison of Python collection types, read when to use lists vs tuples vs sets vs dictionaries.

Common beginner mistakes #

These are some very common problems when learning sets.

Using {} and expecting an empty set #

This creates a dictionary:

value = {}
print(type(value))

Use this instead:

value = set()
print(type(value))

Trying to access a set with an index #

This does not work:

letters = {"a", "b", "c"}
# print(letters[0])

Sets are unordered, so there is no index 0.

Expecting items to stay in insertion order #

A set is not the right choice if you need values to stay in a specific order.

Trying to add a list or dictionary into a set #

This causes an error because lists and dictionaries are mutable.

Using remove() when the item may not exist #

If the item might be missing, discard() is often safer than remove().

Common causes of confusion #

Beginners often run into trouble with sets because they:

  • Confuse sets with lists because both store multiple items
  • Confuse sets with dictionaries because both use curly braces
  • Expect duplicates to remain in the collection
  • Try to index a set like my_set[0]
  • Create an empty dictionary instead of an empty set with {}

Helpful debugging checks #

If a set is not behaving the way you expect, these simple checks can help:

print(my_set)
print(type(my_set))
print(len(my_set))
print(value in my_set)
print(list(my_set))

These checks help you answer questions like:

  • Is this really a set?
  • How many unique items are in it?
  • Does it contain a specific value?
  • What values are currently inside it?

✍️ Try it yourself

Start with the list tags = ["python", "beginner", "python", "tips"]. Turn it into a set to drop the duplicate, add "web" to the set, then check whether "java" is in it.

Show answer
tags = ["python", "beginner", "python", "tips"]
unique_tags = set(tags)
unique_tags.add("web")

print(unique_tags)
print("java" in unique_tags)

Possible output (set order may vary):

{'python', 'beginner', 'tips', 'web'}
False

FAQ #

Does a Python set keep items in order? #

No. A set is unordered, so you should not rely on item position.

Can a set contain duplicate values? #

No. Duplicate values are removed automatically.

How do I create an empty set in Python? #

Use set(). If you use {}, Python creates an empty dictionary.

Can I access a set item by index? #

No. Sets do not support indexing because they are unordered.

When should I use a set instead of a list? #

Use a set when you need unique values or fast membership checks and do not need order.

See also #

Press Esc to close