Skip to main content

How to Get the Size of a Set in Python

A Python set is an unordered collection of unique elements. A common and fundamental operation is to find its "size" or "length," which simply means counting the number of items it contains. The standard and most Pythonic way to do this is with the built-in len() function.

This guide will show you how to use len() to get the size of a set with a clear, practical example.

Understanding "Size" in a Set

The "size" of a set refers to the number of unique elements it holds. Since sets automatically discard duplicate items during creation, the size reflects the count of these distinct elements. The len() function is the universal tool in Python for getting the number of items in any collection, including sets, lists, tuples, and dictionaries.

The Solution: Using the len() Function

To get the size of a set, you simply pass the set object as an argument to the built-in len() function. It returns the number of elements as an integer.

Practical Example

Solution:

# A sample set with 4 unique elements.
# Note that the duplicate '2' is automatically ignored during the set's creation.
my_set = {1, 2, 5, 6, 2}

# Use the len() function to get the size of the set
set_size = len(my_set)

print(f"The original set is: {my_set}")
print(f"The size of the set is: {set_size}")

# You can also use it on an empty set
empty_set = set()
print(f"The size of an empty set is: {len(empty_set)}")

Output:

The original set is: {1, 2, 5, 6}
The size of the set is: 4
The size of an empty set is: 0

Conclusion

Getting the size of a Python set is a simple and direct operation.

Your GoalThe Solution
Find the number of elements in a set.Use the built-in len() function: len(my_set).

The len() function is the standard, efficient, and most readable way to determine the cardinality (size) of a set or any other Python collection.