Python set() Function: Syntax and 6 Examples

If you have repeated values in Python and you want the unique ones, the Python set function is the quickest way to get it. It takes any iterable and gives you back a set without duplicates.

print(set([3, 1, 3, 2, 1]))
# {1, 2, 3}

In this tutorial, I’ll show you set() in six examples: empty sets, removing duplicates, comparing lists, fast lookups and frozensets. Every output comes from Python 3.12.5 in Command Prompt.

Python set() Syntax

set(iterable=(), /)
ParameterRequiredDefaultDescription
iterableNo()Any iterable of hashable items (positional only)

Return value: a new set with each unique item once. Sets have no order and no index.

Note: {} is an empty dict, not a set. More in how to create an empty set in Python.

When to Use set() in Python

  • Removing duplicate IDs or tags
  • Comparing two lists
  • Fast in lookups
  • Counting distinct values

The classic case is removing duplicates from a list in Python.

Example 1: Create an Empty Set with set()

Let me start with the empty set and a string:

empty = set()
print(empty, type(empty))
print(type({}))
print(sorted(set("Mississippi")))

Output:

set() <class 'set'>
<class 'dict'>
['M', 'i', 'p', 's']
Python set function creating an empty set and unique letters from a string
set() is empty; {} is a dict.

How does this work? {} is a dict, not a set. “Mississippi” shrank to four unique letters.

Example 2: How Do I Remove Duplicates from a List in Python?

Order IDs exported from Excel often repeat:

order_ids = [1042, 1017, 1042, 1093, 1017, 1042]
unique_ids = set(order_ids)

print(unique_ids)
print(len(order_ids), "->", len(unique_ids))
print(list(dict.fromkeys(order_ids)))

Output:

{1017, 1042, 1093}
6 -> 3
[1042, 1017, 1093]
Python set function removing duplicate order IDs from a list
Six IDs became three.

How does this work? The set kept 3 of 6 IDs, which len() in Python confirms. dict.fromkeys() keeps the original order.

More options: converting a list to a set in Python.

Example 3: Convert a Tuple or Dictionary to a Set

You can pass any iterable:

stock = {"SKU-101": 12, "SKU-205": 0, "SKU-310": 12}

print(set((5, 5, 10)))
print(sorted(set(stock)))
print(set(stock.values()))

Output:

{10, 5}
['SKU-101', 'SKU-205', 'SKU-310']
{0, 12}

How does this work? A dict gives its keys; .values() gave the counts, with 12 once.

Building dictionaries instead? See the Python dict() function.

Example 4: Compare Two Lists with Python Sets

Which customers bought in both months?

nov = ["Ava", "Liam", "Noah"]
dec = ["Liam", "Emma", "Noah"]

both = set(nov) & set(dec)
new = set(dec) - set(nov)
print("Both months:", sorted(both))
print("New:", sorted(new))
print("All:", len(set(nov) | set(dec)))

Output:

Both months: ['Liam', 'Noah']
New: ['Emma']
All: 4
Python set function comparing November and December customer lists
Intersection, difference and union.

How does this work? & kept shared names, - found new ones, and | combined both.

To merge lists, read merging two lists without duplicates.

Example 5: Fast Membership Checks with set()

Say you hold orders shipping to blocked ZIP codes:

blocked_zips = set([96701, 99501, 96813])
orders = [(5001, 73301), (5002, 99501), (5003, 10001)]

for order_id, zip_code in orders:
    if zip_code in blocked_zips:
        print(order_id, "hold")
    else:
        print(order_id, "ship")

Output:

5001 ship
5002 hold
5003 ship
Python set function checking order ZIP codes against a blocked set
Only order 5002 is held.

How does this work? Only 99501 (Anchorage) matched. Set lookups stay fast at any size.

Why that’s faster than a list: list vs set in Python.

Example 6: Build a Set of Sets with frozenset

Sets can’t hold sets, but frozensets work:

pairs = [("TX", "OK"), ("OK", "TX"), ("CA", "OR")]
regions = set(frozenset(p) for p in pairs)

print(len(regions))
print(frozenset({"TX", "OK"}) in regions)

Output:

2
True

How does this work? Both Texas-Oklahoma tuples became the same frozenset, so two regions remain.

Need order? See Python set vs tuple.

Common Mistakes with Python set()

These are the Python set() errors I see most:

def m1(): return set(2026)
def m2(): return set([["Reno"], ["Boise"]])
def m3(): return set("a", "b")
def m4(): return set([1, 2])[0]
def m5():
    tags = {}
    tags.add("sale")

for n, test in enumerate([m1, m2, m3, m4, m5], 1):
    try:
        test()
    except (TypeError, AttributeError) as err:
        print(f"{n}. {type(err).__name__}: {err}")

Output:

1. TypeError: 'int' object is not iterable
2. TypeError: unhashable type: 'list'
3. TypeError: set expected at most 1 argument, got 2
4. TypeError: 'set' object is not subscriptable
5. AttributeError: 'dict' object has no attribute 'add'
Common Python set function errors: an int, unhashable lists, two arguments, indexing and {}
Five set() errors.
  1. Use {2026} for one number.
  2. Convert inner lists to tuples.
  3. Pass one iterable.
  4. Loop instead of indexing.
  5. Start with set(), not {}.

For indexing, read converting a set to a list in Python.

Wrapping Up the Python set() Function

Python’s set() function turns any iterable into unique items. You can use it to drop duplicates, compare lists and speed up lookups.

Next, browse more Python built-in functions and methods.

Keep working with sets here:

More Questions on Python set() Function

Does set() keep the order of a list?

No. Use list(dict.fromkeys(items)) to keep order.

Why do my set items print in a different order each run?

String hashes are randomized per run. Wrap the set in sorted() for stable output.

What is the difference between set() and frozenset()?

A frozenset can’t change after creation, so it can be a dict key or a set item.

Can a set contain a list or dictionary?

No. Lists and dicts aren’t hashable. Use tuples or frozensets.

Where can I read the full set() reference?

The signature and hashable rules are in set() in the Python docs.