Get the number of elements in an Enum in Python

avatar

Borislav Hadzhiev

Last updated: Jun 17, 2022

banner

Check out my new book

Get the number of elements in an Enum in Python #

Use the len() class to get the number of elements in an enum, e.g. len(Color). The len() function returns the length (the number of items) of an object and can directly be passed an enum.

main.py
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 YELLOW = 3 print(len(Color)) # 👉️ 3

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

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

The result returned from the len() function doesn't count duplicate values.

main.py
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 YELLOW = 3 PURPLE = 1 # 👈️ duplicate value print(len(Color)) # 👉️ 3

Notice that the member with name PURPLE has a value of 1 which is already contained in the enum, so the len() function skips it.

Enums support iteration, so you can use a list comprehension to get a list of all of the enum's names or values.

main.py
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 YELLOW = 3 names = [member.name for member in Color] print(names) # 👉️ ['RED', 'GREEN', 'YELLOW'] values = [member.value for member in Color] print(values) # 👉️ [1, 2, 3]

You can also use a simple for loop if you need to iterate over an enum.

main.py
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 YELLOW = 3 for color in Color: print(color) print(color.name, color.value)
Use the search field on my Home Page to filter through my more than 3,000 articles.