Open In App

Find the length of a set in Python

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a set and our task is to find its length. For example, if we have a = {1, 2, 3, 4, 5}, the length of the set should be 5.

Using len()

len() function in Python returns the number of elements in a set. It provides total count of unique items present in set.

Python
a = {1, 2, 3, 4, 5}
# Returns the number of elements in the set
l = len(a)  
print(l)  

Output
5

Explanation:

  • len(a) function returns the total number of unique elements in the set a, which is 5.
  • Result is stored in the variable "l" and printed to display the length of set.

Using a Loop

Using a loop to find the length of a set involves iterating through each element and incrementing a counter for every item. This manual method replicates the functionality of len().

Python
a = {1, 2, 3, 4, 5}
c = 0
for element in a:
     # Increment the count for each element
    c += 1 
print(c)  

Output
5

Explanation:

  • Loop iterates over each element in set a incrementing counter "c" by 1 for every element.
  • After loop completes "c" holds total number of elements in the set which is printed as length of set.

Using sum()

sum() function can calculate length of a set by summing 1 for each element in set using a generator expression. This method provides same result as len() through manual counting.

Python
a = {1, 2, 3, 4, 5}
# Counts the number of elements
l = sum(1 for _ in a)  
print(l)  

Output
5

Explanation:

  • Sum(1 for _ in a) expression iterates over each element in set "a" and adds 1 for each element.
  • Total sum represents the number of elements in the set which is then printed as length of set.

Using enumerate()

enumerate() function can be used to iterate through a set with an index. By tracking last index during iteration, we can determine the length of set.

Python
a = {1, 2, 3, 4, 5}
for index, _ in enumerate(a):
    pass
    # Since index starts from 0
l = index + 1  
print(l)  

Output
5

Explanation:

  • enumerate(a) function iterates over each element in set a assigning an index to each element.
  • Length is calculated as index + 1 because the index starts from 0 representing total number of elements in set.

Next Article
Practice Tags :

Similar Reads