Skip to main content

Command Palette

Search for a command to run...

Python: Enum vs enumerate()

Shockingly unrelated

Updated
2 min read
Python: Enum vs enumerate()

Shockingly, enum and enumerate() are two totally separate concepts. If it wasn’t for their related names, I wouldn’t have written an article over both. So let’s learn the difference!

Enums!

Enum…is short for enumeration. Lord knows why they chose Enum but they did so we both need to get over it.

Enums are a special kind of class that holds static (constant, not changing) data. So instead of always passing around a string like “north” we can make an Enum that holds the 4 directions. This way you don’t have to worry about typos or capitalization. Below is how you go about that

from enum import Enum, auto

class Ordinal(Enum):
    NORTH = auto()
    SOUTH = auto()
    EAST = auto()
    WEST = auto()

Items in an Enum are called members. Also, in Python constants (variables that don’t change) are traditionally CAPSLOCKED, which is why our members are.

So now, instead of checking if a string is “north”, we can simply check if direction == Ordinals.NORTH:.

About enum.auto()

Enum members can also act as Key-Value pairs. enum.auto() automatically assigns int values to member names. So in the Ordinal example, Ordinal.NORTH.value would be 1. Ordinal.NORTH.name would be “North.”

Values can be any data type. So instead of assigning auto() to NORTH, it could be “N”.

Explore the docs for more on enums ♥️

The enumerate() function

Forget everything you just learned, it’s not related. enumerate() gives us another way to iterate over an object.

Below is a standard for-loop

names = ["Joshua", "Paul"]
for name in names:
    print(name)

Outputs

Joshua
Paul

An enumerate() loop does the same but returns two values per iteration: the current index and its value.

names = ["Joshua", "Paul"]
for index, name in enumerate(names):
    print(index, name)

Outputs

0 Joshua
1 Paul

Explore the docs for more on the enumerate() function 🤩

Python: Enum vs enumerate()