Using random.choice() with Enums in Python

avatar

Borislav Hadzhiev

Last updated: Jun 17, 2022

banner

Photo from Unsplash

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 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
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.