Get a list of all Enum values in Python

avatar

Borislav Hadzhiev

Last updated: Jun 17, 2022

banner

Photo from Unsplash

Get a list of all Enum values in Python #

Use a list comprehension to get a list of all enum values, e.g. values = [member.value for member in Sizes]. On each iteration, access the value attribute on the enum member to get a list of all of the enum's values.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 values = [member.value for member in Sizes] print(values) # 👉️ [1, 2, 3] names = [member.name for member in Sizes] print(names) # 👉️ ['SMALL', 'MEDIUM', 'LARGE']
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

In the first example, we created a list containing all of the values in the enum.

In the second example, we used the name attribute to create a list containing all of the names in the enum.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes.SMALL.name) # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 1

You can use the same approach if you need to get a list of tuples containing the name and value of each enum member.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 result = [(member.name, member.value) for member in Sizes] # 👇️ [('SMALL', 1), ('MEDIUM', 2), ('LARGE', 3)] print(result)

The first element in each tuple is the name, and the second - the value of the enum member.

Use the in operator if you need to check if a value is in an enum.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 values = [member.value for member in Sizes] print(values) # 👉️ [1, 2, 3] if 2 in values: # 👇️ this runs print('2 is in values')

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise it evaluates to False.

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

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 for size in Sizes: print(size) print(size.name, size.value)
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.