How To Get The Number Of Elements In An Enum In Python

Get the number of elements in an Enum in Python

To get the number of elements in an Enum in Python, we have two methods: Using the len() function and using for loop. Check out the details below to get more information.

To get the number of elements in an Enum in Python

Using the len() fucntion

To get the number of elements in an enum in Python, you could use the len() function in Python. The len() function will return the number of items in an object. 

Syntax:

len(object)

Parameters: 

  •   object: is an object, must be a sequence or a collection.

Return value: return value is the number of items in an object.

Code example:

Firstly, we must import Enum. Then create the class Enum Animals. Secondly, we will create a count variable to get the length of the Animals Enum.

from enum import Enum

class Animals(Enum):
    shark = 1
    dolphin = 2
    elephant = 3
    dog = 4

# Get the number of elements in Enum by using the len() method    
count = len(Animals);

print("The total of an element in Animals Enum is: ", count)

Output

The total of an element in Animals Enum is:  4

Example 2: 

In this example, we will create the Enum with a duplicate object. And the len() method will skip this element to be duplicated. The len() function not count duplicate value. 

from enum import Enum

# Create the Animals Enum class with five element
class Animals(Enum):
    shark = 1
    dolphin = 2
    elephant = 3
    dog = 4
    cat = 4 

# The len() function did not count duplicate value 4 in the dog and cat element   
count = len(Animals);

print("The total of an element in Animals Enum is: ",count) # expected is 4

Output

The total of an element in Animals Enum is:  4

Using for loop to count the number of elements

Another simple way to get the number of elements in an Enum is to use for loop. We will loop to all elements in Enum and use the count variable to calculate the sum of the element in the Enum.

Example

from enum import Enum

class Animals(Enum):
    shark = 1
    dolphin = 2
    elephant = 3
    dog = 4
    
count = 0

# Count all elements in Animals Enum
for animals in Animals:
    count +=1

print("The total of an element in Animals Enum is: ",count)

Output

The total of an element in Animals Enum is:  4

Summary

In this tutorial, we have explained how to get the number of elements in an Enum in Python. We always hope this tutorial is helpful to you. Leave your comment here if you have questions or comments about improving the article.

Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *