To determine the size of a set in Python, use the built-in len() function. This returns the number of unique elements in the set, as sets automatically eliminate duplicates.
Example:
my_set = {1, 2, 3, 4}
size = len(my_set)
print(size) # Output: 4For an empty set,
len()returns0:empty_set = set() print(len(empty_set)) # Output: 0
Note: The term "size" in this context refers to the number of elements, not memory usage. If you need the memory footprint (in bytes), use
sys.getsizeof(set)orset.__sizeof__().
To answer the question in the title: Use len() to get the size of a set.
Semantically that is a bit weird, as a set is an unordered collection, and the length analogy kind of breaks down (we are actually measuring cardinality), but in the spirit of Python using len to get the size of all kinds of collections is easy to remember and it is quite obvious what the statement means.