To get the length of a Set in Python, you can use the len() function.
The length of the Set means the number of elements in the Set, which is the size of that specific object. Based on the length, you can create custom logic that will help perform various operations.
Syntax
len(set)
Example
# Define a set new_set = {2, 4, 6, 8} # Get the length of the set print(len(new_set)) # 4
The above Set contains four elements.
Empty Set
What if the Set is empty? If you pass that, what will be the output? Let’s find out.
# Define a set empty_set = set() # Get the length of the set print(len(empty_set)) # 0
If a Set has no elements, meaning it has 0 elements.
Handling Duplicates
The len() is a basic function that returns the count of distinct elements, as a Set automatically removes duplicates.
# Define a set main_set = {11, 21, 21, 19, 19, 11} # Get the length of the set print(len(main_set)) # 3
We got the length three because Set can’t allow duplicate elements. Only elements 11, 21, and 19 are unique, and the length() only reflects unique elements.
Nested Set
You cannot create a nested Set because Sets are not hashable, and that’s why it cannot be an element of a Set. And that’s why you cannot use the len() function on a nested Set because it does not exist.
Set of tuples
If you are working with a Set of tuples and some of them are duplicates, it will remove the duplicate tuples and return the count of unique tuples.
# Define a set of tuples main_set = {(11, 21), (21, 19), (21, 19)} # Get the length of the set print(len(main_set)) # 2
Counting unique words
If you have a large string and you want to find unique words in that sentence, you can use the len(set). But how, let’s find out.
text = "What is Python? How to learn Python? Why Python is popular?" words = text.split() unique_words = set(words) print(unique_words) # Output: {'popular?', 'What', 'learn', 'to', 'Python?', 'is', 'How', 'Python', 'Why'} print(f"Unique words: {len(unique_words)}") # Output: Unique words: 9
Frozen Sets
You can use fronzenset, which behaves like a set, but you cannot modify it after creation. The len() function also returns the number of elements of the frozenset.
frozen = frozenset([11, 21, 31]) print(len(frozen)) # Output: 3 # frozen.add(4) # Raises AttributeError
Performance and Efficiency
The len() function has a time complexity of O(1). Even if the Set is large, it is still efficient.
import random # Deduplicate a list of 1 million elements big_list = [random.randint(1, 100) for _ in range(1_000_000)] unique_count = len(set(big_list)) print(unique_count) # Output: 100
That’s all!