How to Create a Python Empty Set
Learn the correct way to create a Python empty set, why {} creates an empty dictionary, and how to use empty sets effectively in real code.

Creating an empty set in Python is a common operation, but the syntax is easy to get wrong. The expression {} creates an empty dictionary, not a set. To create an empty set, you must call set() with no arguments. This distinction is a frequent source of bugs, especially for developers coming from other languages where {} might represent an empty collection.
Creating an Empty Set with set()
The only direct way to create an empty set in Python is to use the built-in function set():
empty_set = set()
print(type(empty_set)) # <class 'set'>
print(len(empty_set)) # 0The set() constructor returns a new empty set object. This is the canonical and recommended approach. It works in every Python version that supports sets, which is all modern Python 3.x releases.
If you already have an iterable, you can pass it to set() to create a set with initial elements, but for an empty set, no arguments are needed.
Why {} Does Not Create an Empty Set
In Python, curly braces have two roles: they define dictionary literals and set literals. When you write {}, the interpreter sees an empty dictionary because the set literal syntax requires at least one element to disambiguate from a dictionary. For example:
d = {}
print(type(d)) # <class 'dict'>To create a non-empty set with a literal, you include elements separated by commas:
s = {1, 2, 3}
print(type(s)) # <class 'set'>But there is no empty set literal. The grammar does not allow {,} or any other empty set notation. This is a deliberate design choice in the language. The only way to express an empty set is set(). Understanding this asymmetry is critical when you initialize collections conditionally or pass defaults to functions.
Practical Use Cases for Empty Sets
Empty sets are useful whenever you need a mutable, unordered collection of unique elements that starts with nothing. Common scenarios include:
- Tracking visited nodes in a graph traversal without duplicating work.
- Accumulating unique user IDs from a stream of events.
- Storing a set of tags or categories that will be populated dynamically.
- Serving as a default value for optional parameters in functions.
For example, consider a function that collects unique words from a list:
def unique_words(words):
result = set()
for word in words:
result.add(word)
return resultHere, result starts as an empty set and grows as words are processed. The add method ensures duplicates are ignored automatically.
Adding and Removing Elements from an Empty Set
Once you have an empty set, you can modify it with the standard set methods. The add method inserts a single element, while update adds multiple elements from an iterable:
s = set()
s.add('apple')
s.update(['banana', 'cherry'])
print(s) # {'apple', 'banana', 'cherry'}To remove elements, use remove (raises KeyError if missing) or discard (does nothing if missing). For example:
s.discard('banana') # no error if absent
s.remove('apple') # raises KeyError if 'apple' is not presentThese operations are useful when you need to maintain a working set that changes over time. Starting with an empty set gives you a clean slate and avoids the overhead of constructing a set with placeholder values.
Performance and Memory Considerations
Creating an empty set with set() is a lightweight operation. The set starts empty and grows internally as elements are added. There is no meaningful performance difference between the resulting set object and one created from a non-empty literal. The main performance consideration is how you use the set afterward. Membership tests (in) are O(1) on average, which makes sets ideal for deduplication and existence checks.
One subtle memory point: if you create many empty sets in a loop, each set() call allocates a new object. If you only need a read-only collection, consider using a frozenset, but for a mutable empty set, set() is the only option. Reusing a single set object is more efficient than creating new ones repeatedly, so avoid creating empty sets inside tight loops unless you actually need separate objects.
Common Pitfalls and How to Avoid Them
The most common pitfall is using {} to create a set and then discovering that the code behaves differently because the variable is a dictionary. This often surfaces when you try to call set methods like add or discard:
# Wrong
s = {}
s.add(1) # AttributeError: 'dict' object has no attribute 'add'Another pitfall is using set() with an argument when you intend an empty set. For example, set([]) creates an empty set, but it is less readable and does an unnecessary iteration. Similarly, set('') creates an empty set, but it can be confusing because it looks like you are converting a string.
A third issue is assuming that a set literal with one element behaves like a tuple. {1} is a set containing the integer 1, not a tuple. This is correct, but it can surprise developers who are new to Python.
To avoid these mistakes, always use set() for an empty set and reserve {} for dictionaries. When reviewing code, look for {} assignments and verify the intended type.
Using Empty Sets in Type Hints and Data Structures
In modern Python (3.9+), type hints can use the built-in generic form set[str] to describe a set of strings. For example:
def process_items(seen: set[str]) -> None:
# 'seen' is expected to be a set of strings
pass
# Caller can pass an empty set
process_items(set())For older Python versions, typing.Set[str] is the equivalent generic annotation. Both forms mean the same thing at the type-checking level.
When you need a default value for a mutable parameter, avoid using an empty set as a default argument because mutable defaults are shared across calls. Instead, use None and create a fresh set inside the function:
def track(seen=None):
if seen is None:
seen = set()
# now 'seen' is a new empty set each callThis pattern prevents subtle bugs where state leaks between function invocations. It is a standard idiom in Python and works well with empty sets.
Empty sets also appear as initial values in data structures like dictionaries of sets. For instance, you might build a mapping from keys to sets of values:
from collections import defaultdict
groups = defaultdict(set)
groups['a'].add(1)
groups['a'].add(2)
print(groups['a']) # {1, 2}The defaultdict automatically creates a new empty set when a key is accessed for the first time, which simplifies code that would otherwise need explicit initialization checks.
Understanding how to create and use a Python empty set correctly is a small but essential skill. The set() constructor is the only direct way to get an empty set, and knowing when to use it prevents common errors and leads to clearer, more maintainable code.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.