Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to get Enum value by index

Tags:

python

enums

I have an Enum of days_of_the week in Python:

class days_of_the_week(str, Enum):
  monday = 'monday'
  tuesday = 'tuesday'
  wednesday = 'wednesday'
  thursday = 'thursday'
  friday = 'friday'
  saturday = 'saturday'
  sunday = 'sunday'

I want to access the value using the index.

I've tried:

days_of_the_week.value[index]
days_of_the_week[index].value
days_of_the_week.values()[index]

and so on... But everything I tried didn't returned me the value of enum (eg. days_of_the_week[1] >>> 'tuesday')

Is there a way?

like image 366
Sara Briccoli Avatar asked Mar 08 '26 18:03

Sara Briccoli


1 Answers

IIUC, you want to do:

from enum import Enum

class days_of_the_week(Enum):
    monday = 0
    tuesday = 1
    wednesday = 2
    thursday = 3
    friday = 4
    saturday = 5
    sunday = 6

>>> days_of_the_week(1).name
'tuesday'
like image 129
not_speshal Avatar answered Mar 10 '26 08:03

not_speshal