Focused practice · 8 min read

Python Enum Exercises: Names, Values, and Lookup

An enum gives a fixed set of names to a concept such as status, color, or direction. The members are real objects, not loose strings, so comparisons and lookups become explicit.

Define a closed set of members

Subclass Enum and assign names to values. The class body defines the available members. By convention, member names are uppercase, while the stored values can be strings, numbers, or other hashable objects.

from enum import Enum
class Status(Enum):
    OPEN = "open"
    CLOSED = "closed"
print(Status.OPEN.value)

Names with stable values

Name and value are different

The member is the enum object. Its name is the identifier used in the class, and its value is what was assigned. Printing the member shows a qualified name, while .value gives the underlying data.

from enum import Enum
class Color(Enum):
    RED = "red"
member = Color.RED
print(member.name)
print(member.value)
print(member)

Three related views

Look up by value or by name

Calling the enum with a value returns the matching member and raises ValueError when no member matches. Square-bracket lookup uses the member name and raises KeyError instead. Choose the lookup that matches the input you have.

from enum import Enum
class Color(Enum):
    RED = "red"
    GREEN = "green"
print(Color("green"))
print(Color["RED"])

Two directions of lookup

Iterate in definition order

Iterating an enum yields its members in the order they were defined. This is useful for building menus or validating a set of choices. Aliases are skipped during normal iteration unless you inspect the members mapping directly.

from enum import Enum
class Size(Enum):
    SMALL = 1
    MEDIUM = 2
    LARGE = 3
print([item.name for item in Size])

Definition order is preserved

Use auto for generated values

auto lets Python assign values when the exact number does not matter. It keeps the source focused on the member names. Do not rely on the generated numbers as a stable external format.

from enum import Enum, auto
class Step(Enum):
    START = auto()
    FINISH = auto()
print(Step.START.value)
print(Step.FINISH.value)

Let Python number the members

Your practice checklist

Common questions

Is an enum member equal to its value?

No. Color.RED is not equal to the string red. Compare with Color.RED.value when you need the underlying value.

Can two names share a value?

Yes. The second name becomes an alias for the first member, and normal iteration skips the alias.

Should I store enum values in a database?

Store a deliberate stable value, not the member object. Changing the value later can break stored data, so treat it as part of your format.

Practice enums

12 questions on members, name and value, lookup, iteration, and auto.

Open practice

Keep reading: