The Wayback Machine - https://web.archive.org/web/20250211011809/https://www.geeksforgeeks.org/find-the-length-of-a-set-in-python/
Open In App

Find the length of a set in Python

Last Updated : 07 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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. The idea is use len() in Python

Python
s1 = {1, 2, 3}
print(len(s1))

s2 = {}
print(len(s2))

s3 = {"geeks", "for"}
print(len(s3))

Output
3
0
2

More examples to show how to find length of a set

Example 1:

Python
s = set()  
print("The length of set is:", len(s))

# Adding element and tuple to the Set 
s.add(8) 
s.add(9) 
print("The length of set is:", len(s))

s.add((6, 7)) 
print("The length of set is:", len(s))

Output:

The length of set is: 3

Example 2:

Python
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).


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg