Python len(set) function


The len(set) function in Python is used to determine the number of elements in a set. It returns an integer that represents the size of the set, which is the total count of unique elements it contains.

Syntax

length = len(set)
  • set: This is the set object for which you want to find the length.

Return Value

  • Returns an integer representing the number of unique elements in the set.

Example

Here are some examples to illustrate how len(set) works:

1. Basic Example

# Creating a set my_set = {1, 2, 3, 4, 5} # Getting the length of the set length = len(my_set) print(length) # Output: 5

In this example, my_set contains five unique elements, so len(my_set) returns 5.

2. Example with Duplicate Elements

Sets automatically remove duplicate elements, so len() will only count unique items.

# Creating a set with duplicate elements my_set = {1, 2, 2, 3, 4} # Getting the length of the set length = len(my_set) print(length) # Output: 4

Here, although my_set was initialized with a duplicate 2, it only contains four unique elements (1, 2, 3, 4), so len(my_set) returns 4.

3. Length of an Empty Set

If you use len() on an empty set, it will return 0.

# Creating an empty set empty_set = set() # Getting the length of the empty set length = len(empty_set) print(length) # Output: 0

Use Cases

  • Data Validation: Checking if a set contains the expected number of unique elements can be useful in data validation tasks.
  • Counting Unique Items: The len(set) function is commonly used to determine the number of unique items in a collection, which is useful in various applications, such as analyzing data sets or inventory management.

Summary

The len(set) function is a straightforward and efficient way to determine the number of unique elements in a set in Python. It provides valuable information about the set's size, which can be useful in various programming scenarios, including data analysis and validation.