Python – Set Length

Python – Set Length

To get the length of a given Set in Python, you can use len() built-in function. Call len(), and pass the given set as argument. The len() function returns an integer representing the number of items in the Set.

For example, the following expression returns the length of the set set_1.

len(set_1)

Examples

1. Finding the length of a given set in Python

In this example, we take a set in set_1 with some initial values, and find the length of the set using len() function.

Python Program

set_1 = set({"apple", "banana", "cherry"})
set_1_length = len(set_1)
print(f"Length of the set : {set_1_length}")
Run Code Copy

Output

Length of the set : 3

Since there are three elements in the given set, len(set_1) returned an integer value of 3.

2. Finding the length of an empty set in Python

In this example, we take an empty set in set_1, and find the length of the set using len() function. Since the length of an empty set is zero, len() function should return 0.

Python Program

set_1 = set()
set_1_length = len(set_1)
print(f"Length of the set : {set_1_length}")
Run Code Copy

Output

Length of the set : 0

Summary

In this tutorial of Python Sets, we learned how to get the length of a given Set in Python, using len() built-in function, with examples.

Related Tutorials

Code copied to clipboard successfully 👍