This post will discuss how to find the size of a set in Python.

1. Using len() function

The Pythonic way to get the total number of elements in a set is using the built-in function len(). This function returns a non-negative value representing the number of items in an object that has a length attribute. Here is an example of how to use this function on a set:

Download  Run Code

 
If the set is empty, the len() function returns zero as expected.

Download  Run Code

 
Note that a set in a boolean context is treated as False if empty and True otherwise. Therefore, we should avoid using the len() function in boolean contexts to check if a set is empty.

Download  Run Code

 
The len() function is implemented with __len__ function. Although not very Pythonic, the __len__ function can be called directly:

Download  Run Code

2. Using collections.Counter() class

Another way to find the size of a Python set is to use the collections.Counter() class from the collections module. We can create a Counter object from a set and then use its __len__() function to find the size of the set. Here is an example on how to use this function:

Download  Run Code

 
However, it requires importing an external module and it may not be very efficient.

That’s all about finding the size of a set in Python.

 
Also See: Why len(x) is chosen over x.len()?