Skip to content

Python enum get all values | Example code

  • by

Use the IntEnum or loop through it to enum get all values in Python. The resulting list contains the enum members, which are instances of the enum class, so they have both a name and a value.

Example Get all values from an enum class

A simple example program gets all values from an enum class. You have to also use the list and map function in this example.

from enum import IntEnum


class Country(IntEnum):
    Afghanistan = 93
    Albania = 355
    Algeria = 213


country_codes = list(map(int, Country))
print(country_codes)

Output:

Python enum get all values

Another example

Using list comprehension.

from enum import Enum


class Color(Enum):
    RED = 1
    BLUE = 2


res = [e.value for e in Color]
print(res)

Output: [1, 2]

Or you can get all the values of an enum by using the list() function on the enum class.

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

values = list(Color)

print(values)  # Output: [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]

Do comment if you have any doubts or suggestions on this Python enum topic,

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading