Check if a value exists in an Enum in Python

avatar

Borislav Hadzhiev

Last updated: Jun 17, 2022

banner

Photo from Unsplash

Check if a value exists in an Enum in Python #

To check if a value exists in an enum in Python:

  1. Use a list comprehension to get a list of all of the enum's values.
  2. Use the in operator to check if the value is present in the list.
  3. The in operator will return True if the value is in the list.
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 enum values') else: print('2 is NOT in enum values') print(100 in values) # 👉️ False

We used a list comprehension to get a list of the enum's values.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

The last step is to use the in operator to check if a specific value is in the list.

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.

If you need to check if a value is not in an enum, negate the conditional with not.

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 100 not in values: # 👇️ this runs print('100 is NOT in enum values')

You can use the same approach if you need to check if a specific name is present in an enum.

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

Instead of accessing the value attribute, we used the name attribute to get a list of the enum's names.

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.