Get the length of a Set in Python

avatar

Borislav Hadzhiev

Last updated: Jun 14, 2022

banner

Photo from Unsplash

Get the length of a Set in Python #

Use the len() function to get the length of a set, e.g. result = len(my_set). The len() function returns the length (the number of elements) of an object and can be passed a sequence (a list, string, tuple, range or bytes) or a collection (a dictionary, set, or frozen set).

main.py
my_set = {'a', 'b', 'c'} print(len(my_set)) # 👉️ 3

The len() function returns the length (the number of items) of an object.

Set objects are an unordered collection of unique elements, so they don't support indexing and slicing. If you need to support indexing and slicing, use square brackets to create a list instead.

If you need to count the elements in a set that satisfy a condition, use a list comprehension to get a subset of elements that match the condition and pass the results to the len() function.

main.py
my_set = {1, 2, 3, 4, 5} result = len([x for x in my_set if x > 3]) print(result) # 👉️ 2

The example gets the number of set elements that are greater than 3.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

The len() function is always guaranteed to return the correct length of the set, regardless if you add or remove elements.

main.py
my_set = {'a', 'b', 'c'} my_set.add('d') print(my_set) # 👉️ {'d', 'a', 'b', 'c'} print(len(my_set)) # 👉️ 4 my_set.remove('d') print(my_set) # 👉️ {'a', 'b', 'c'} print(len(my_set)) # 3

You can also use the len() function to check if a set is empty.

main.py
my_set = set() if len(my_set) == 0: # 👇️ this runs print('set is empty') else: print('set is NOT empty')

If a set has a length of 0, then it's empty.

You might also see examples online that check whether the set is truthy (to check if it contains at least 1 item), which is more implicit.

main.py
my_set = set() if my_set: print('set is NOT empty') else: # 👇️ this runs print('set is empty')

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

Notice that an empty set is a falsy value, so if the set is empty, the else block is run.

If you need to check if the set is empty using this approach, you would negate the condition with not.

main.py
my_set = set() if not my_set: # 👇️ this runs print('set is empty') else: print('set is NOT empty')
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.