Sets in Python: Operations, Operators and When They’re Faster

A set holds unique items with no order. Duplicates are discarded automatically, and you can’t index into one.

numbers = {1, 2, 2, 3} print(numbers) # {1, 2, 3} ← the duplicate is gone

That’s the obvious part. The reason to care is speed.

Checking whether an item is in a set takes the same time regardless of size. Checking a list scans it. On a hundred thousand items, that’s the difference between 0.00004 seconds and 0.67 — roughly seventeen thousand times.

This guide covers creating sets, the four operators, what can’t go in one, and when a set is the wrong choice.

The short version
Written withCurly braces — {1, 2}, never square brackets
Empty setset() — because {} is a dictionary
Mutable?Yes — the immutable version is frozenset
Membership testConstant time, whatever the size
Can’t holdLists, dictionaries or other sets

Creating a set

tags = {"python", "web", "python"} print(tags) # {'python', 'web'}numbers = set([1, 2, 2, 3]) print(numbers) # {1, 2, 3}empty = set() # NOT {} print(type({})) # <class 'dict'>

⚠️ Curly braces, not square brackets. [1, 2] creates a list; {1, 2} creates a set.

And the empty case is a genuine trap: {} creates an empty dictionary, not an empty set. The only way to get an empty set is set().

What you can’t do with a set

Three limitations, and they’re the reason a set isn’t always the answer.

tags = {"python", "web"}tags[0] # TypeError: 'set' object is not subscriptable

No indexing, because there’s no order. The display order isn’t guaranteed and shouldn’t be relied on.

No duplicates, which is the point — but it means a set can’t count occurrences.

And only hashable items:

{[1, 2]} # TypeError: unhashable type: 'list'{{1, 2}} # TypeError: unhashable type: 'set'{(1, 2)} # tuples are fine {frozenset([1, 2])} # and frozensets

Anything mutable can’t go in a set, because its hash could change while it sits there. Tuples and frozenset work; lists, dictionaries and sets don’t.

⚠️ Sets are mutable

Worth stating plainly, because it’s often claimed otherwise:

tags = {"python"} tags.add("web") print(tags) # {'python', 'web'} ← it changed

A set can be modified after creation. The immutable version is frozenset:

frozen = frozenset([1, 2]) frozen.add(3) # AttributeError: 'frozenset' object has no attribute 'add'

Use frozenset when you need a set as a dictionary key, or inside another set — the two cases where mutability disqualifies a regular set.

Adding and removing

tags = {"python"}tags.add("web") # adds one item tags.update({"api"}) # adds each item from another collection tags.discard("web") # removes if present — no error if absent tags.remove("api") # removes — KeyError if absent tags.clear() # empties it

⚠️ All of these return None. They modify the set in place, so tags = tags.add("x") sets tags to None — the same pattern covered in our guide on methods that return None.

remove() vs discard()

The difference is what happens when the item isn’t there:

{1, 2}.discard(99) # nothing happens {1, 2}.remove(99) # KeyError: 99

Use discard() when absence is fine, remove() when it’s a bug worth knowing about.

pop() removes an arbitrary item

{10, 20, 30}.pop() # 10 — but don't rely on which

⚠️ It isn’t “the last added” or “the first” — a set has no order, so which item comes out is an implementation detail. If you need a specific item, a set is the wrong structure.

The four operators

The four set operations in Python shown as Venn diagrams: union with the pipe, intersection with the ampersand, difference with the minus, and symmetric difference with the caret

Each has a method and a symbol; they do the same thing.

a = {1, 2, 3, 4} b = {3, 4, 5, 6}a | b # {1, 2, 3, 4, 5, 6} union — everything a & b # {3, 4} intersection — in both a - b # {1, 2} difference — in a, not in b a ^ b # {1, 2, 5, 6} symmetric — in one, not both
SymbolMethodReturns
|union()Every item from both
&intersection()Only what’s in both
-difference()In the first, not the second
^symmetric_difference()In one or the other, not both

⚠️ There is no + for sets. Writing {1, 2} + {3} raises TypeError — union is |, not +. It’s the most common mistake coming from lists, where + does concatenate.

Comparing sets

{1, 2} <= {1, 2, 3} # True subset {1, 2, 3} >= {1, 2} # True superset {1, 2}.isdisjoint({3, 4}) # True nothing in common

The real reason to use a set

Membership testing doesn’t depend on size.

import timeitbig_list = list(range(100_000)) big_set = set(range(100_000))timeit.timeit(lambda: 99999 in big_list, number=1000) # 0.673s timeit.timeit(lambda: 99999 in big_set, number=1000) # 0.00004s

Roughly seventeen thousand times faster, and the gap widens as the collection grows.

The reason is structural. A list checks item by item until it finds a match — O(n). A set computes the item’s hash and jumps straight to where it would be — O(1), regardless of how many items there are.

⚠️ The practical rule: if you’re checking membership against the same collection more than a handful of times, convert it to a set once and test against that.

# Slow: scans the list on every iteration for item in incoming: if item in known_list: ...# Fast: one conversion, then constant-time checks known = set(known_list) for item in incoming: if item in known: ...

The conversion itself costs O(n) once. After two or three lookups, it has already paid for itself.

Removing duplicates

The most common use of sets, and it has a caveat.

values = [3, 1, 2, 1, 3]list(set(values)) # [1, 2, 3] ← order lost list(dict.fromkeys(values)) # [3, 1, 2] ← order preserved

⚠️ set() discards the order, and the result may come out in any sequence. When order matters, dict.fromkeys() is the right tool — dictionaries have preserved insertion order since Python 3.7.

And a subtlety with numbers

{1, 1.0, True} # {1} ← all three collapse into one

A set considers items duplicates when they compare equal, and in Python 1 == 1.0 == True. Which of the three survives depends on which was inserted first — so a set of mixed numeric types can silently lose data.

Set comprehensions

{x * 2 for x in range(5)} # {0, 2, 4, 6, 8} {word.lower() for word in ["Ana", "ana"]} # {'ana'} ← deduped

Same syntax as a list comprehension, with braces instead of brackets — and duplicates are removed as it builds.

Set, list or dictionary?

StructureMembership testUse when
setO(1)You only need to know whether something is there
listO(n)Order matters, or duplicates are meaningful
dictO(1)You need a value attached to each item

A dictionary is a set with values attached — same hashing, same constant-time lookup, plus something stored against each key.

⚠️ When a set is the wrong choice: when you need position, when duplicates carry information (counting occurrences), or when the items aren’t hashable. Our guide on lists covers that side.

Where sets help on a server

Two cases where the structure choice shows up in production.

Filtering against a blocklist. Checking each incoming request against a list of blocked IPs scans the list every time. With ten thousand entries and a hundred requests per second, that’s a million comparisons per second — and the CPU limit on a shared plan notices. A set makes it a hundred lookups.

Deduplicating imports. Processing a file of records and checking “have I seen this ID?” against a list is quadratic — a hundred thousand rows means five billion comparisons. With a set it’s linear, and the difference is minutes versus hours.

⚠️ Both are the same mistake: using a list where only membership matters. The fix is one line — known = set(known) before the loop.

The wrong data structure hits the CPU limit first

Scanning a list where a set would do turns a hundred lookups into a million — and on a shared plan, that’s throttling rather than a crash. Copahost VPS plans give you dedicated CPU, root access, and your choice of Python version. From €3.99/month, with snapshots.

See VPS plans

Frequently asked questions

What is a set in Python?

A collection of unique, unordered items, written with curly braces: {1, 2, 3}. Duplicates are discarded automatically, and you can’t access items by index because there’s no order.

Are sets mutable in Python?

Yes. You can add and remove items after creating one. ⚠️ The immutable version is frozenset, which you need when a set has to be a dictionary key or live inside another set.

How do I create an empty set?

With set(). {} creates an empty dictionary, not a set — it’s one of the sharper traps in the language, because the syntax looks like it should work.

What’s the difference between remove() and discard()?

What happens when the item isn’t there. remove() raises KeyError; discard() does nothing. Use discard() when absence is acceptable, remove() when it signals a bug worth catching.

Why can’t I use + to join two sets?

Because sets have no + operator — it raises TypeError. Union is |, or the union() method. It’s the most common mistake coming from lists, where + concatenates.

What do |, &, - and ^ do?

| is union (everything from both), & is intersection (only what’s in both), - is difference (in the first, not the second), and ^ is symmetric difference (in one or the other, not both).

Why is a set faster than a list for checking membership?

Because a list scans item by item while a set computes a hash and jumps straight to the answer. On a hundred thousand items, that’s about seventeen thousand times faster — and the gap grows with size.

Why can’t I put a list inside a set?

Because set items must be hashable, and anything mutable isn’t — its hash could change while it sits in the set. Tuples and frozenset work; lists, dictionaries and sets don’t.

Does set() preserve the order of my items?

No. Converting a list to a set discards the order, and the result may come out in any sequence. When order matters, use list(dict.fromkeys(values)) — dictionaries have preserved insertion order since Python 3.7.

Why did {1, 1.0, True} become just {1}?

Because a set treats items as duplicates when they compare equal, and in Python 1 == 1.0 == True. All three collapse into one, and which survives depends on insertion order — so a set of mixed numeric types can silently lose data.

Which item does pop() remove from a set?

An arbitrary one. ⚠️ It isn’t “the last added” or “the first” — a set has no order, so the choice is an implementation detail you shouldn’t rely on. If you need a specific item, a set is the wrong structure.

When should I use a list instead of a set?

When order matters, when you need to access items by position, or when duplicates carry information — counting how many times something appears is impossible in a set, because it only keeps one of each.

Conclusion

A set holds unique, unordered items — and the uniqueness is the obvious half. The half that matters in production is the speed.

Three things carry it. Union is |, not + — sets have no + at all. An empty set is set(), because {} builds a dictionary. And sets are mutable; the immutable one is frozenset, which you need for a set inside a set or as a dictionary key.

And the reason to reach for one: checking membership takes the same time whatever the size. On a hundred thousand items, a set answers roughly seventeen thousand times faster than a list — because it hashes and jumps, rather than scanning.

If you’re testing “is this in that collection” more than a couple of times, convert once. It’s a single line, and it’s the difference between a loop that finishes and one that doesn’t.

Share the Post:
Picture of Gustavo Gallas

Gustavo Gallas

Graduated in Computing at PUC-Rio, Brazil. Specialized in IT, networking, systems administration and human and organizational development​. Also have brewing skills.