How to Iterate Over Enum in Python: Simple Guide
To iterate over an
enum.Enum in Python, use a for loop directly on the enum class. Each loop gives you an enum member, and you can access its .name and .value properties.Syntax
Use a for loop on the enum class to get each member. Access .name for the member's name and .value for its value.
python
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 for color in Color: print(color.name, color.value)
Output
RED 1
GREEN 2
BLUE 3
Example
This example shows how to define an enum and loop through all its members to print their names and values.
python
from enum import Enum class Status(Enum): PENDING = 'pending' RUNNING = 'running' COMPLETED = 'completed' for status in Status: print(f'Status name: {status.name}, value: {status.value}')
Output
Status name: PENDING, value: pending
Status name: RUNNING, value: running
Status name: COMPLETED, value: completed
Common Pitfalls
One common mistake is trying to iterate over enum members by looping over enum.__members__ keys or values incorrectly. Also, avoid iterating over the enum instance instead of the enum class.
Wrong way:
for item in Status.PENDING:
print(item)This causes an error because Status.PENDING is a single enum member, not iterable.
Right way:
for item in Status:
print(item)python
from enum import Enum class Status(Enum): PENDING = 'pending' RUNNING = 'running' # Wrong way - will raise TypeError # for item in Status.PENDING: # print(item) # Right way for item in Status: print(item.name, item.value)
Output
PENDING pending
RUNNING running
Quick Reference
| Action | Code Example |
|---|---|
| Define enum | class Color(Enum): RED = 1 |
| Iterate enum | for c in Color: print(c.name, c.value) |
| Access name | color.name |
| Access value | color.value |
Key Takeaways
Use a for loop directly on the enum class to iterate over members.
Access each member's name with .name and value with .value.
Do not try to iterate over a single enum member instance.
Enum members are iterable only via the enum class, not instances.
Use enum.Enum from the standard library to create enums.