Skip to content
PythonAdvanced Python Building Blocksbeginner22 min read

Enums and Named Tuples

Represent fixed choices with enums and create readable, tuple-like records with NamedTuple.

In this lesson, you will learn

  • ✓Explain when to use an Enum to represent a fixed set of named choices.
  • ✓Distinguish an enum member's name from its associated value.
  • ✓Access, compare, and iterate over enum members and handle invalid values.
  • ✓Create NamedTuple records with named fields and type annotations.
  • ✓Explain NamedTuple indexing, unpacking, immutability, and default values.
  • ✓Choose appropriately between an enum, a named tuple, and an ordinary tuple.

1. What Is an Enum?

An enumeration, usually called an enum, represents a fixed collection of named members. It is useful when a value should come from a known set of choices, such as PENDING, APPROVED, and REJECTED.

Python provides Enum in the standard-library enum module. To define an enum, import Enum and create a class that inherits from it. Each attribute assigned inside the class becomes an enum member.

An enum member has a name and an associated value. In `Status.PENDING = 'pending'`, the member name is PENDING and its value is the string 'pending'. The name is the identifier used in Python code; the value is the data associated with that member.

Enum members make code easier to read because `Status.APPROVED` communicates intent more clearly than an unexplained string such as 'approved'. They also provide a central place to define the allowed choices.

Defining an enum does not automatically validate every external input in your application. If a user or API supplies a status, your program must still decide how to convert or reject that input.

Define and use an enum

Define and use an enum
python
from enum import Enum
 
class Status(Enum):
PENDING = 'pending'
APPROVED = 'approved'
REJECTED = 'rejected'
 
print(Status.PENDING)
print(Status.APPROVED)
Output
Status.PENDING Status.APPROVED

`Enum` is imported from Python's standard-library enum module. `Status` defines three named members. `Status.PENDING` refers to an enum member, not just the string 'pending'. Printing a member displays its enum class and member name.

Note

Enum values do not have to be strings. They can be integers or other suitable objects. Choose values that make sense for your application and avoid relying on their type without a reason.

2. Comparing, Iterating Over, and Looking Up Enum Members

Enum members can be compared directly with other members. For an ordinary Enum, compare members of the same enum when checking which choice is selected.

For example, `current_status == Status.APPROVED` checks whether `current_status` is the APPROVED member. Comparing the member with the plain string 'approved' is not the same check: an ordinary Enum member is not equal to its string value.

You can iterate over an enum class to visit its defined members. This is useful for displaying available choices or testing each defined status.

You can also construct an enum member from its associated value by calling the enum class with that value, such as `Status('approved')`. If no member has that value, Python raises `ValueError`.

When reading a member by its declared name, use square-bracket lookup such as `Status['APPROVED']`. If the name does not exist, Python raises `KeyError`. Remember that name lookup uses the member name, whereas value lookup uses the associated value.

Compare enum members

Compare enum members
python
from enum import Enum
 
class Status(Enum):
PENDING = 'pending'
APPROVED = 'approved'
 
current = Status.APPROVED
 
if current == Status.APPROVED:
print('Order approved')
else:
print('Order not approved')
Output
Order approved

`current` refers to the APPROVED enum member. The comparison checks whether it equals `Status.APPROVED`. The condition is true, so the first message is printed.

3. Handle Invalid Enum Values

Enum classes are useful for representing a defined set of choices, but external input may not match one of those choices.

Suppose an application receives a status string from a form. Calling `Status(user_input)` attempts to find the enum member associated with that value. A valid value produces a member; an unknown value raises `ValueError`.

Use a try/except block when invalid values are expected and should be handled gracefully. Catch the specific exception you expect instead of catching every possible exception without a reason.

Do not confuse a member's name with its value. If the declared name is APPROVED and the associated value is 'approved', `Status['APPROVED']` looks up by name, while `Status('approved')` looks up by value.

Safely handle an unknown value

Safely handle an unknown value
python
from enum import Enum
 
class Status(Enum):
PENDING = 'pending'
APPROVED = 'approved'
 
user_input = 'cancelled'
 
try:
status = Status(user_input)
print(status.name)
except ValueError:
print('Unknown status')
Output
Unknown status

`user_input` contains 'cancelled', which is not an enum value defined in Status. `Status(user_input)` raises `ValueError`. The except block handles that specific error and displays `Unknown status`. The program does not print `status.name` because the failed assignment does not complete.

Caution

When converting data received from a user or an external service, validate it or catch the expected lookup error. Do not assume every incoming string is a valid enum value.

4. What Is a Named Tuple?

A tuple groups multiple values into one object. A normal tuple such as `('Asha', 22)` is compact, but it does not explain what each position means unless the reader already knows the structure.

A named tuple adds field names to a tuple-like record. Python's `typing.NamedTuple` lets you define a class with named fields and type annotations.

For example, a Student record can have a `name` field and an `age` field. You can access these fields using `student.name` and `student.age` instead of remembering that the name is at index 0 and the age is at index 1.

A NamedTuple instance is still tuple-like: it supports indexing, iteration, unpacking, and comparison with other tuples by their elements. It also provides named attributes, making the data easier to read.

NamedTuple is a good choice for simple records whose fields should not be reassigned after construction. If you need mutable attributes or more involved behavior, consider whether a regular class or a dataclass would be a better fit.

Create a named tuple

Create a named tuple
python
from typing import NamedTuple
 
class Student(NamedTuple):
name: str
age: int
 
student = Student('Asha', 22)
 
print(student.name)
print(student.age)
Output
Asha 22

`Student` defines a named-tuple type with two fields. `name: str` describes the intended type of the name field. `age: int` describes the intended type of the age field. `Student('Asha', 22)` constructs an instance with those field values. Dot notation accesses each field by its name.

Note

The NamedTuple class syntax shown here is provided by the standard-library typing module and works on supported modern Python versions.

5. Named Tuples Support Unpacking but Are Immutable

Because a named tuple is tuple-like, you can unpack its fields into separate variables. The number of target variables must match the number of values being unpacked.

You can also pass a named tuple to code that expects an ordinary tuple of compatible length and contents. Named tuples provide extra field names without abandoning tuple behavior.

Named tuples are immutable. After an instance has been created, you cannot assign a new value to one of its fields. For example, assigning `student.age = 23` raises `AttributeError`.

Immutability applies to the tuple's field bindings. If a field refers to a mutable object, that object's contents may still be mutable. For simple records containing strings and integers, this distinction is usually straightforward.

If you need to update a named-tuple field, create a new instance with the desired values rather than attempting to change the existing instance.

Unpack a named tuple

Unpack a named tuple
python
from typing import NamedTuple
 
class Student(NamedTuple):
name: str
age: int
 
student = Student('Ravi', 24)
name, age = student
 
print(name)
print(age)
Output
Ravi 24

`student` contains two values in a fixed order. `name, age = student` unpacks the first field into `name` and the second into `age`. The print statements display the unpacked values on separate lines.

Caution

Do not treat NamedTuple fields as mutable attributes. Reassignment to a field is not supported; create a new instance when you need a different record.

6. Named Tuple Defaults and Type Hints

NamedTuple fields can have default values. Fields with defaults must come after fields without defaults in the class definition.

A default makes the corresponding constructor argument optional. If a field has a default, you can omit that argument when constructing the record and Python uses the default value.

Type annotations document the intended field types, but they do not automatically validate all values passed to the constructor. For example, a field annotated as `age: int` does not by itself guarantee that an integer was supplied.

For simple records with fixed fields, NamedTuple provides a concise combination of named access and tuple behavior. A dataclass is often more suitable when you want records that can be mutable or have richer class behavior.

Use a default field value

Use a default field value
python
from typing import NamedTuple
 
class Product(NamedTuple):
name: str
price: float
in_stock: bool = True
 
first = Product('Notebook', 49.5)
second = Product('Pen', 10.0, False)
 
print(first.in_stock)
print(second.in_stock)
Output
True False

`name` and `price` have no defaults and must be supplied. `in_stock` defaults to True, so the first instance can omit that argument. The second instance explicitly passes False, overriding the default for that instance. The field order places the field with a default after the fields without defaults.

Note

NamedTuple type annotations are useful documentation and support static type checking. They should not be mistaken for automatic runtime input validation.

7. Enum vs NamedTuple vs Ordinary Tuple

An Enum and a NamedTuple solve different problems. An Enum represents one choice from a fixed set of named members. A NamedTuple groups several related values into a single record.

Use an Enum when the possible choices are known in advance, such as PENDING, APPROVED, and REJECTED. Use a NamedTuple when you need a record such as a Point with x and y fields or a Student with name and age.

Use an ordinary tuple for a simple ordered group of values when field names would add little clarity. If you repeatedly need to remember what each tuple position means, a NamedTuple can improve readability.

Neither Enum nor NamedTuple replaces input validation or good program design. Choose the structure that best expresses the data and rules your application actually needs.

Choose the right structure

Choose the right structure
python
from enum import Enum
from typing import NamedTuple
 
class OrderStatus(Enum):
PENDING = 'pending'
SHIPPED = 'shipped'
 
class OrderSummary(NamedTuple):
order_id: int
status: OrderStatus
 
order = OrderSummary(101, OrderStatus.SHIPPED)
 
print(order.order_id)
print(order.status.name)
print(order.status.value)
Output
101 SHIPPED shipped

`OrderStatus` defines the finite set of allowed status members. `OrderSummary` groups an order ID and a status into one record. The `status` field contains an enum member, so its name and value can be accessed through that member. This example combines the two tools because each serves a distinct purpose.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Confusing an enum member's name with its value.

Why it happens: An enum member's name is its identifier in the enum definition, while its value is the data assigned to that member.

Incorrect Approach
script.py
python
Confusing an enum member's name with its value.
Correct Solution
script.py
python
Use `.name` for the declared member name and `.value` for its associated value.

Key takeaway: Use `.name` for the declared member name and `.value` for its associated value.

#2 Comparing an ordinary Enum member directly with its associated string.

Why it happens: Ordinary Enum members are not automatically equal to their associated string values; compare the member or explicitly inspect its .value.

Incorrect Approach
script.py
python
Comparing an ordinary Enum member directly with its associated string.
Correct Solution
script.py
python
Compare enum members with the corresponding enum member, or explicitly access `.value` when comparing with the underlying value is intended.

Key takeaway: Compare enum members with the corresponding enum member, or explicitly access `.value` when comparing with the underlying value is intended.

#3 Assuming an unknown enum value produces a default member automatically.

Why it happens: Looking up an unknown value raises ValueError by default, so provide explicit fallback or error handling if unknown values are expected.

Incorrect Approach
script.py
python
Assuming an unknown enum value produces a default member automatically.
Correct Solution
script.py
python
Handle invalid value lookups explicitly, for example by catching `ValueError` when constructing a member from an unknown value.

Key takeaway: Handle invalid value lookups explicitly, for example by catching `ValueError` when constructing a member from an unknown value.

#4 Using the wrong lookup method for an enum.

Why it happens: Enum lookup by value uses EnumClass(value), while lookup by name uses EnumClass['NAME']; choose based on the input you have.

Incorrect Approach
script.py
python
Using the wrong lookup method for an enum.
Correct Solution
script.py
python
Use `Status['APPROVED']` to look up by declared member name and `Status('approved')` to look up by associated value.

Key takeaway: Use `Status['APPROVED']` to look up by declared member name and `Status('approved')` to look up by associated value.

#5 Using numeric indexes for every named-tuple field even when the meaning is not obvious.

Why it happens: NamedTuple fields have names that communicate meaning, so named access is usually clearer than numeric indexing.

Incorrect Approach
script.py
python
Using numeric indexes for every named-tuple field even when the meaning is not obvious.
Correct Solution
script.py
python
Prefer readable attribute access such as `student.age` when the field's meaning matters.

Key takeaway: Prefer readable attribute access such as `student.age` when the field's meaning matters.

#6 Trying to assign a new value to a NamedTuple field.

Why it happens: NamedTuple instances are tuple-like and immutable, so create a new instance rather than assigning to a field.

Incorrect Approach
script.py
python
Trying to assign a new value to a NamedTuple field.
Correct Solution
script.py
python
NamedTuple instances are immutable. Construct a new instance when you need different field values.

Key takeaway: NamedTuple instances are immutable. Construct a new instance when you need different field values.

#7 Placing a field without a default after fields with defaults.

Why it happens: Like ordinary function parameters, required named-tuple fields must precede fields with defaults.

Incorrect Approach
script.py
python
Placing a field without a default after fields with defaults.
Correct Solution
script.py
python
Define required fields first and fields with defaults afterward.

Key takeaway: Define required fields first and fields with defaults afterward.

#8 Assuming type annotations validate all NamedTuple constructor arguments.

Why it happens: NamedTuple annotations help static analysis but do not automatically validate every runtime argument or nested value.

Incorrect Approach
script.py
python
Assuming type annotations validate all NamedTuple constructor arguments.
Correct Solution
script.py
python
Use annotations for documentation and static analysis. Perform explicit runtime validation if the application requires it.

Key takeaway: Use annotations for documentation and static analysis. Perform explicit runtime validation if the application requires it.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is an Enum in Python?
Answer:
Enum is a standard-library base class used to define a collection of named members. It is useful for representing fixed choices such as statuses, roles, or traffic-light states.
Q2:What is the difference between an enum member's name and its value?
Answer:
The name is the identifier declared in the enum class, such as APPROVED. The value is the associated object assigned to that member, such as the string 'approved'. Access them through `.name` and `.value`.
Q3:How do you retrieve an enum member by name or by value?
Answer:
Use `Status['APPROVED']` to retrieve a member by its declared name. Use `Status('approved')` to retrieve a member by its associated value. An unknown name raises KeyError, while an unknown value raises ValueError.
Q4:What is a NamedTuple?
Answer:
NamedTuple, available from the typing module, creates tuple-like records with named fields and optional type annotations. It allows both readable attribute access and tuple operations such as indexing and unpacking.
Q5:What is the difference between a tuple and a NamedTuple?
Answer:
Both are tuple-like and immutable, but a NamedTuple gives fields descriptive names. For example, `point.x` is usually easier to understand than `point[0]` when working with coordinates.
Q6:Are NamedTuple instances mutable?
Answer:
No. Their fields cannot be reassigned after construction. When a different record is needed, create a new instance with the desired values.
Q7:Can a NamedTuple field have a default value?
Answer:
Yes. Define a default in the field declaration, placing fields with defaults after fields without defaults. Callers may omit those trailing arguments and the defaults are used.
Q8:Do NamedTuple annotations enforce field types at runtime?
Answer:
Not automatically. They document intended types and support static analysis. If an application requires strict validation of incoming data, implement explicit runtime checks.
Q9:When would you choose an Enum instead of a NamedTuple?
Answer:
Choose an Enum when representing one of a fixed set of choices. Choose a NamedTuple when grouping related fields into a record, such as a student's name and age. They can also be combined when a record contains a field that must be one of several enum choices.
Q10:How does a NamedTuple differ from a dataclass?
Answer:
A NamedTuple is an immutable tuple-like record that supports indexing, unpacking, and tuple comparison. A dataclass is generally a better fit when you need mutable fields or richer record behavior and do not require tuple semantics.

Key takeaways

  • Enum represents a fixed set of named members and makes choices more explicit.
  • Use `.name` to access an enum member's declared name and `.value` to access its associated value.
  • Iterate over an enum to visit its defined members.
  • Look up enum members by name with square brackets or by value by calling the enum class.
  • Handle invalid enum lookups with the appropriate exception handling when necessary.
  • NamedTuple groups related values into an immutable, tuple-like record with named fields.
  • Named tuples support attribute access, indexing, unpacking, and tuple-like operations.
  • Fields with defaults must follow fields without defaults.
  • Enum, NamedTuple, ordinary tuples, and dataclasses solve different problems; choose according to the structure and behavior your program needs.
  • Type annotations document intended types but do not automatically validate all runtime values.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: