What is random.choice() in Python?

The in-built choice() function from the random module randomly selects an element from a sequence, such as a list.

Syntax

random.choice(seq)

Arguments

  • seq: the non-empty sequence from which the element is selected, such as a list, string, etc.

Return value

This function returns an element from the sequence. If the sequence is empty, IndexError is raised.

import random
# picking a random element from defined list
testList = [1, 2, 3, 4]
print("List: ", testList)
element = random.choice(testList)
print("Selected element from list: ", element)
# picking a random letter from string
testStr = "Educative"
print("Str: ", testStr)
element = random.choice(testStr)
print("Selected element from string: ", element)
# using choice() to pick a random number from a range:
num = random.choice(range(0, 101))
print("Random number from 0 to 100: ", num)

Note: the output will be different every time the code is run.

Free Resources