Python random choice() Method

Python random.choice() method returns a randomly selected element from the specified sequence. The sequence can be a string, a range, a list, a tuple, or any other kind of sequence.

To find a random element from a sequence, you can use the “random.choice()” method.

Syntax

random.choice(sequence)

Parameters

sequence: It can be a list, string, tuple, or iterable object.

Return Value

The random choice() function returns the single element from the sequence. If we pass the empty list or sequence to the random.choice() function will raise the IndexError: Cannot choose from the empty sequence.

Example 1: How to Use random.choice() method in Python

import random

numberList = [11, 19, 21, 29, 46]
print("Random item from the list is: ", random.choice(numberList))

Output

➜ pyt python3 app.py
Random item from the list is: 11
➜ pyt python3 app.py
Random item from the list is: 46
➜ pyt python3 app.py
Random item from the list is: 19
➜ pyt python3 app.py
Random item from the list is: 29

Example 2: Selecting multiple elements

The random.choice() method only returns a single element from the list. To randomly select more than one element from the list or set, I recommend using the random.sample() or random.choices() instead.

import random

numberList = [11, 19, 21, 29, 46, 10, 18, 37]
print("Random item from the list is: ", random.choices(numberList, k=4))

Output

Random item from the list is: [10, 29, 37, 46]

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.