Skip to content

How to Get the Size of a Set in Python

Learn how to quickly determine the number of unique elements in a Python set using the built-in len() function with clear examples and best practices.

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:

my_set = {1, 2, 5, 6, 2}

set_size = len(my_set)

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

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 Goal The 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.

Navigation