Python – Choose Random Element from Sequence

Python – random choice()

To choose a random element from given sequence in Python, use choice() method of random package.

The sequence could be a list, tuple, range, string, etc.

The sequence must be non-empty, else Python raises IndexError.

In this tutorial, we shall learn how to choose an item/element from a given non-empty sequence using random.choice() method.

Syntax – random.choice()

Following is the syntax of choice() method in random module.

f = random.choice(seq)

where

ParameterDescription
seq[Mandatory] A non-empty sequence.

choice() method returns a randomly chosen element from the given sequence.

Example 1 – Choose a Random Element from List

In this example, we shall use random.choice() method to choose an element randomly from a given list of numbers.

Python Program

import random

seq = [2, 3, 5, 7, 11]
x = random.choice(seq)
print(x)
Run

Output

5

Example 2 – Choose a Random Element from Tuple

In this example, we shall use random.choice() method to choose an element randomly from a given tuple of strings.

Python Program

import random

seq = ('apple', 'banana', 'mango')
x = random.choice(seq)
print(x)
Run

Output

mango

Example 3 – Choose a Random Character from String

In this example, we shall use random.choice() method to choose a character randomly from a given string.

Python Program

import random

seq = 'apple'
x = random.choice(seq)
print(x)
Run

Output

p

Summary

In this tutorial of Python Examples, we learned how to choose an element from a given sequence using random.choice() method, with the help of well detailed example programs.