Python Program to Find Set Length

In this article, we show how to write a Python Program to find set length with or without built-in functions. There is a built-in set len() function that returns the length, which is reliable and effective. Apart from that, we can use the native for loop and while loops to find the length using custom coding.

Python Program to find the length of a set using the len() function

The built-in set len() function allows users to pass a set object as an argument and count the total number of unique set elements. Next, the len() function returns the set length as an integer value. The syntax of the Python set len() function to find the set length is

len(Set)

In this example, we declared an integer list with five unique numbers. Next, we utilized the built-in set len() function to determine its length.

s = {10, 25, 136, 44, 150}
print(len(s))
5

Using the len() function to find the length of a set of strings

In the example below, we declared a set of unique fruit items (strings). Next, the len() function finds the length of a set of string words.

s = {'apple', 'banana', 'Mango', 'kiwi'}
print(len(s))
4

Python Program to find the length of a mixed set

In the following example, we declared a mixed set of strings, integers, floating-point numbers, and Boolean values. Next, the set len() function returns the length without any issues. Remember, if you replace False with True on a set, it will consider True as 1, and if there is a duplicate, it returns 5.

s = {'Apple', 2.46, 45, 'Banana', False, 1}
print(len(s))
6

Using the len() function to find the length of a nested set

As we all know, we can’t create a nested set, but we can nest tuples inside the set. When we use the Python set len() function to find the length of a set with nested tuple items, it considers the top-level items as one. It means every nested tuple inside a set is considered as one item and counted as 1. As there are three nested tuples inside the main set, it returns True.

s = {(11, 22), (33, 44), (55, 66)}
print(len(s))
3

We can use a for loop to iterate over each nested tuple inside a set and apply the len() function on nested items to get the total set elements. Here, the for loop iterates over the set elements. Inside the loop, the len(i) finds the length of each set element (nested tuple).

s = {(11, 22), (33, 44), (55, 66, 77)}
print(len(s))
count = 0
for i in s:
    count += len(i)
print(count)
3
7

Python Program to find set length of user-defined items

In this Program, we declared an empty set and allowed the user to enter the set items. Here, the for loop iterates over the set, and the add() function adds those items to the set. Next, the len() function calculates the set length.

intSet = set()
number = int(input("Enter the Total Set Items = "))
for i in range(1, number + 1):
    value = int(input("Enter the %d Set value = " %i))
    intSet.add(value)
    
print("Set Items = ", intSet)

intSetLength = len(intSet)
print("Set Length = ", intSetLength)
Python Program to Find Set Length

How to find the length of an empty set in Python?

The built-in set len() function is brilliant in identifying empty sets and returns 0 as the output. By default, the len() will count the total number of set elements. As there are none to count, it returns 0.

s = set()
print(len(s))
0

How to find the length of a set with duplicate items?

When we apply the set len() function on a set with duplicate items, the len() function counts the distinct items in it. By default, the set removes duplicates; the len() function won’t count them when returning the set length.  

In the example below, there are seven set elements. However, the len() function returns 5 because duplicates are removed by set. Try print(s), it shows only five distinct items.

s = {1, 2, 1, 3, 2, 4, 5}
print(len(s))
5

Python Program to Find set length using a for loop

Apart from the traditional len() function, we can use the native for loop approach to find the set length. In this example, we declared a set of integer values. Next, the for loop iterates over the set elements from start to end.

On each iteration, the count variable increments by 1. It means, for each set element, the count value increments by 1 to find the set length. Finally, the print() function prints the set length stored in the count variable.

s = {10, 25, 50, 75, 100}

count = 0
for _ in s:
    count += 1
print(count)
5

Python Program to find set length using list comprehension

In the example below, we used list comprehensions to find the length of a given set. Here, the list comprehension creates a new list with 1 for each set of elements. It means the output of the list comprehension is [1, 1, 1, 1] because there are four set elements. Next, the sum() finds the sum of the list items or set length, and it is four.

s = {10, 20, 30, 40}

count = sum([1 for _ in s])
print(count)
4

Using a generator and sum

Unlike the above, it does not create a list. Here, we used the generator expression that creates a generator object with 1’s for each set element. Next, the sum() will calculate the total, which is the set length in Python.

s = {"ab", "cd", "ef", "gh"}

count = sum(1 for _ in s)
print(count)
4

Python set length using the enumerate() function

Unlike the regular for loop, the enumerate function automatically increments the counter variable value. In this example, we use the enumerate() function to iterate over the set elements. Here, n is the counter value, which will automatically increment for each item. By default, it starts with 0, so set the enumerate() second argument to 1.

s = {10, 20, 30, 40, 50}

for n, _ in enumerate(s, 1):
    pass

print(n)
5

Python Program to find set length using a while loop

In the following example, we utilized the while loop to find the length of a given set. Here, we used iter() to convert the given set into an iterator. Within the while loop, on each iteration, the next() function calls the next item from the iter (set). On each repeated call, the count value increments by 1. Once there are no items, it raises the StopIteration error, and the except call the break statement to exit the while loop. 

products = {"laptop", "PC", "phone", "tablet"}
count = 0
n = iter(products)
while True:
    try:
        next(n)
        count += 1
    except StopIteration:
        break

print(count)
4

Python Program to find set length using map() and sum()

In the example below, we utilized the map() function and the lambda expression to find the length of a given set. Here, the map() function iterates over the set elements and returns a map object. The lambda expression assigns 1 for each set item. Next, the sum() calculates the total (1 + 1 + 1 + 1), which is the set length.

products = {"laptop", "PC", "phone", "tablet"}

count = sum(map(lambda c: 1, products))
print(count)
4

Using functools.reduce() function

The following examples use the reduce() function from the functools library to find the length of a given set in Python. Here, the reduce() function starts with 0. For every set item, it increments by 1, and the final value is the set length.

from functools import  reduce
s = {10, 30, 60, 90, 120, 150}

count =reduce(lambda n, _: n + 1, s, 0)
print(count)
6

TIP: If you convert a set to a list, then you have a few more options to find its length. To convert a set to a list, use the list() function. Please refer to the list length article for the available options to calculate the set length.