The choice method of the random module

The choice method of the random module returns a random element from a sequence (string, list, tuple). In the method parameter, we specify the sequence we need.

Syntax

pythonimport random

random.choice(subsequence)

Example

Let's get any of the elements of the string:

pythontxt = 'abcde'
print(random.choice(txt))

Result of code execution:

python'e'

Example

Now let's get a random list element:

pythonlst = [1, 2, 3, 4, 5]
print(random.choice(lst))

Result of code execution:

python5

Example

Let's print any of the elements of the tuple:

pythontpl = ('1', '2', '3', '4', '5')
print(random.choice(tpl))

Result of code execution:

python'4'

See also

  • method shuffle of module random,
    which shuffles the sequence
  • method random of module random,
    which returns a pseudo-random number
  • method sample of module random,
    which returns a random sample of elements from a sequence