Kodeclik Blog
Sets are a data structure in Python that let you store unordered collections of unique items. They are useful when you do not want duplicates—for example, when storing unique IDs, tags, or numbers.
The most common way is to call the built-in set() function:
This creates an empty set that you can later fill with values.
If you want to get a little fancy, starting with Python 3.5 you can create an empty set using set unpacking syntax (PEP 448):
There are other variants that work:
If you already have a non-empty set, you can clear it using the clear() method:
Alternatively, you could re-assign it to a new empty set:
Indeed you can! You can assign one empty set to another:
This is another valid way of initializing a set as empty.
All sets in Python have the type set, regardless of whether they contain integers, strings, or booleans.
Actually, no, you cannot. In Python, {} creates an empty dictionary, not an empty set.
So always use set() (or the fancier unpacking trick) when you want an empty set.
As discussed earlier, in Python, {} creates an empty dictionary, not a set. To create an empty set, always use set(). If you try type({}), the output will be <class 'dict'>, while type(set()) gives <class 'set'>.
The {} syntax is reserved for dictionaries in Python, even though non-empty sets can be defined with curly braces (e.g., {1, 2, 3}). For empty sets, you must use set() to avoid confusion and ensure correct data types.
You can check if a set is empty in several ways. First, you can use boolean context:
Alternatively, you can use the len() function:
Finally, you can compare it to another empty set:
All these methods are commonly used and work reliably.
- Use set() to declare an empty set.
- {} will give you an empty dictionary, not a set.
- To empty an existing set, use clear() or reassign with set().
- Empty sets have the type set.
- Python >= 3.5 allows alternate literal unpacking tricks like {*()} to create empty sets.
Enjoy this blogpost? Want to learn Python with us? Sign up for 1:1 or small group classes.