59 of 151 menu

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

import random random.choice(subsequence)

Example

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

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

Result of code execution:

'e'

Example

Now let's get a random list element:

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

Result of code execution:

5

Example

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

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

Result of code execution:

'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
byenru