random.choice

Full name
random.choice
Library
random
Syntax

random.choice(seq)

Description

The random.choice function returns a random value extracted from the sequence passed as an argument. If this sequence is empty, the function generates an IndexError.

Parameters
  • seq: Sequence from which to extract the random value.
Result

The random.choice function returns a value of a type that matches that of the element extracted from the sequence.

Examples

We can extract a random day of the week with the following code:

day = random.choice(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
day
'Tuesday'

In this case, the return type is string :

type(day)
str

In this second example we pass a list of real numbers as a sequence:

n = random.choice([2.5, 3.7, 6.1, 8.9])
n
8.9

In this case, the return type is float :

type(n)
float

Note that the sequence can be made up of elements of different types:

random.choice([1, 3.1415, "Pi", True])
True
Submitted by admin on Thu, 03/11/2021 - 17:05