Ad space (banner)
🐍Python Lessons
Lesson 42 / 69

Enum (Enumerated Types) Basics

This lesson covers how to use Python's Enum, so you can safely work with a fixed set of choices. It's written for anyone searching "Python Enum tutorial".

Inheriting from Enum in the enum module lets you build an "enumeration" representing a fixed set of choices. It's useful whenever you want to restrict a value ahead of time to a known set — like a traffic light having only red, green, and yellow. Using named constants, rather than scattering raw strings or numbers throughout your code, makes the code's intent clearer and helps prevent typos.

The sample code defines an Enum class called Color with three choices, RED, GREEN, and BLUE, retrieving the actual value with Color.RED.value, and getting a list of every choice with a list comprehension. Note that Color.RED itself is an Enum member object — you need .value to get the underlying value.

A common beginner mistake is confusing an Enum member with its .value. Color.RED == "red" is False, while Color.RED.value == "red" is True. Not understanding this distinction can lead to a subtle comparison bug.

It's also handy that your editor's autocomplete can immediately show you every choice defined in an Enum. This is a commonly used pattern in real work for representing a value that only ever takes on a fixed set of forms — like an order status or a user's permission level.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)