Python set length: How to Get Length of Set in Python

0
8
Python set length - How to Get Length of Set in Python

Python set is used to store multiple unordered and unchangeable elements in a single variable. A set is one of the Python objects that can be written with braces ({}).

Python set length

To get the length of the set in Python, use the len() function. The len() is a built-in Python function that returns an object’s length (the number of items). An object can be a Python iterator like List, Dictionary, Set, Tuple, or String.

Syntax

len(set)

Arguments

The len() function takes a single mandatory argument, the set data type.

Example

first_set = set()

first_set.add("Millie")
first_set.add("Steve")
first_set.add("Dustin")

print("The length of set is:", len(first_set))

Output

The length of set is: 3

To create a set in Python, use the set() function. To add elements in the Python set, use the set.add() function. Using the len() function, we get the length of the set, which is three because the set has only three elements.

The len() function always returns the accurate length of the set whether you add or remove items from the set.

How does the len() function work in Python?

The len() is a built-in Python function that works in o(1) time as the set is an object and has a member to store its size. It returns the length of an object. The length is the number of elements contained by an iterator.

Count conditional items in Python Set

To count the items in a set that satisfies a condition, use the list comprehension to get a subset of items that match the condition and pass the output to the len() function.

first_set = {11, 21, 31, 41, 51, 61, 71, 81, 91}

output = len([x for x in first_set if x > 50])

print("The length of set containing values greater than 50 is:", output)

Output

The length of set containing values greater than 50 is: 5

In this example, we count the length of a set with elements greater than 50. It won’t count the elements which are less than 50. Using the list comprehension and len() method, we can get the length of the set satisfied by the conditions.

Python set empty

To check if a set is empty in Python, use the len() function. Compare the length of a set to 0, and if it returns True, the set is empty. Otherwise, it is not empty.

seat = set()

if len(seat) == 0:
 print("The set is empty")
else:
 print("The set is NOT empty")

Output

The set is empty

That’s it for this tutorial.

Related posts

Python tuple length

Python list length

Python string length

Python array length

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.