std::set

Is set() the Same as {} in Python?

No. In Python, set() makes an empty set while {} makes an empty dict. Learn how to tell them apart, create sets correctly and avoid the common mistakes.

On this page
  1. Checking the type of each
  2. Creating a set with values
  3. Mistakes that come from the difference
  4. Set operators
  5. Empty braces in C++

No. In Python, set() makes an empty set and {} makes an empty dictionary. The two look alike, but they are different types, and the difference matters as soon as you call a set method on the result.

Checking the type of each

empty_set = set()
empty_dict = {}

print(type(empty_set))   # <class 'set'>
print(type(empty_dict))  # <class 'dict'>

Python’s language reference defines an empty pair of braces as an empty dictionary. A set display needs at least one value inside the braces, so the only way to get an empty set is to call set().

Creating a set with values

Put values inside braces, or pass an iterable to set():

colors = {"red", "green", "red"}
letters = set("banana")

print(colors)   # {'red', 'green'}, in some order
print(letters)  # {'a', 'b', 'n'}, in some order

Repeated values are stored once. Sets are unordered, so the order Python prints them in is not something to rely on, and it can change between runs.

Mistakes that come from the difference

Calling a set method on an empty pair of braces fails:

seen = {}
seen.add("apple")  # AttributeError: 'dict' object has no attribute 'add'

Use seen = set() instead. An empty set and an empty dict are both falsy, so if not seen: treats them the same way. If the type matters, check it with isinstance(seen, set).

Set elements have to be hashable, so a list cannot go inside one:

bad = {[1, 2]}   # TypeError: unhashable type: 'list'
good = {(1, 2)}  # a tuple is hashable, so this works

Set operators

Sets support operators for the usual set math:

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

print(a | b)  # union: {1, 2, 3, 4}
print(a & b)  # intersection: {2, 3}
print(a - b)  # difference: {1}

Python sets are unordered. For the C++ container, which always keeps its keys sorted, see sets in c.

Empty braces in C++

In C++, braces do not mean a dictionary by themselves. The declared type decides what {} creates:

std::set<int> s = {};       // empty set
std::map<int, int> m = {};  // empty map

The key-value counterpart of a set in C++ is std::map, which dictionary in c covers.

The complete guide to std::set

Sets in C++: How std::set Works
Read the guide

Keep exploring

Guides from other topics

All topics →

The sizeof Operator in C++

Learn how the sizeof operator in C++ works: what it returns in bytes, how it handles arrays, pointers and structs, and common mistakes to avoid.

sizeof 6 min read

Bitwise XOR in C++

Learn how the bitwise XOR operator (^) in C++ works, with a truth table, code examples, and common uses such as toggling bits and swapping values.