Monday, November 24, 2025
HomeLanguagesFind the length of a set in Python

Find the length of a set in Python

In Python, a Set is a collection data type that is unordered and mutable. A set cannot have duplicate elements. Here, the task is to find out the number of elements present in a set. See the below examples.

Examples:

Input: a = {1, 2, 3, 4, 5, 6}
Output: 6

Input: a = {'Geeks', 'For'}
Output: 2

The idea is use len() in Python

Find-Length-of-set

Example 1:

Python3




# Python program to find the length
# of set
  
set1 = set()  
    
# Adding element and tuple to the Set 
set1.add(8) 
set1.add(9) 
set1.add((6, 7)) 
  
print("The length of set is:", len(set1))


Output:

The length of set is: 3

Example 2:

Python3




n = len({1, 2, 3, 4, 5})
  
print("The length of set is:", n)


Output:

The length of set is: 5

How does len() work?
len() works in O(1) time as the set is an object and has a member to store its size. Below is description of len() from Python docs.

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

RELATED ARTICLES

Most Popular

Dominic
32410 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6909 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6865 POSTS0 COMMENTS
Umr Jansen
6852 POSTS0 COMMENTS