Using random.choice() with Enums in Python

avatar

Borislav Hadzhiev

Fri Jun 17 20221 min read

Using random.choice() with Enums in Python #

To use the random.choice() method with enums:

  1. Pass the enum to the list() class to convert it to a list.
  2. Pass the list to the random.choice() method to get a random enum member.
main.py
from enum import Enum import random class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 my_list = list(Sizes) # 👇️ [<Sizes.SMALL: 1>, <Sizes.MEDIUM: 2>, <Sizes.LARGE: 3>] print(my_list) print(random.choice(my_list)) # 👉️ Sizes.LARGE print(random.choice(my_list)) # 👉️ Sizes.SMALL

We used the list() class to convert the the enum to a list of enum members.

The random.choice method takes a sequence and returns a random element from the non-empty sequence.

Since an enum isn't a sequence, we can't directly pass one to the random.choice() method.

The list contains enum members, so you can access the name or value properties to get the name or value of the randomly picked enum member.

main.py
from enum import Enum import random class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 my_list = list(Sizes) # 👇️ [<Sizes.SMALL: 1>, <Sizes.MEDIUM: 2>, <Sizes.LARGE: 3>] print(my_list) print(random.choice(my_list).name) # 👉️ SMALL print(random.choice(my_list).value) # 👉️ 2
Use the search field on my Home Page to filter through my more than 1,000 articles.