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

Thee idea is use len() in Python

Find-Length-of-set

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

The length of set is: 3

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.