How to find the Python Set Size?

In this short blog post, I’ll show you how to find the size of set in Python. 

What is a Python set?
A set is a collection data type that cannot have duplicate elements. It’s unordered and mutable, allowing different set operations, such as union, intersection, difference, to be performed on it.

Depending on the various use-cases, you’d want to know how to calculate the set size or length in Python.

How to calculate the Python set size?

To find the size of set in Python, use the built-in len() method. The len() method can be used with any other collection or sequence too, and it calculates how many elements the given collection contains. 

The syntax looks like this:
len(X)
where X is the Python set defined with set() or with curly braces {}.

In our case, the len() method calculates how many elements the Python set contains. Since set allows only distinct elements, by calculating the set length in Python you’ll get the exact number of distinct elements.

Examples – using the len() method to find the length of set in Python

Let’s take a look at a few examples. In the first one, we’ll calculate the size of the set containing different numbers, strings, and even tuples.

set_example = {1, 2, 3, 4, 5}
len(set_example)  # 5

set_example = {'a', 'b', 'c'}
len(set_example)  # 3

set_example = {(1, 2), (3, 4), (5, 6)}
len(set_example)  # 3

The set can also be defined by using the set() keyword. You add elements by calling the add() method and passing each element as an argument. Calculating the set length is the same as before.

set_example = set()
set_example.add(1)
set_example.add(2)
set_example.add(3)
len(set_example)  # 3

What if we define equal elements inside of a set? First, the set will dispose of all duplicate elements. Then by calling the len() method, we’ll get the exact number of distinct elements. Note that in the following example there are three 1’s defined inside of a set.

set_example = {1, 1, 1, 2, 3, 4, 5}
len(set_example)  # 5

If the set is empty, the len() method will, logically, return 0 as a total number of elements.

set_example = {}
len(set_example)  # 0

It’s as simple as that!