Find size of a set in Python
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:
|
1 2 3 4 5 |
s = {1, 2, 3} n = len(s) print(n) # 3 |
If the set is empty, the len() function returns zero as expected.
|
1 2 3 4 5 |
s = set() n = len(s) print(n) # 0 |
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.
|
1 2 3 4 5 |
s = set() if not s: print('The set is empty') |
The len() function is implemented with __len__ function. Although not very Pythonic, the __len__ function can be called directly:
|
1 2 3 |
s = {1, 2, 3} print(s.__len__()) # 3 |
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:
|
1 2 3 4 5 |
import collections s = {1, 2, 3} n = collections.Counter(s).__len__() print(n) # 3 |
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()?
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)