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 of 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.

Examples

1. Choose a random element from a 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 Code Copy

Output

5

2. Choose a random element from a 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 Code Copy

Output

mango

3. Choose a random character from a 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 Code Copy

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.

Related Tutorials

Code copied to clipboard successfully 👍