Python Random choice() Method

Python random.choice() method is used to randomly select an item from a sequence such as a list, tuple, or string.

Passing a List to Python Random choice() Method

Syntax

random.choice(sequence)

Parameters

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

Return Value

It returns the single element from the sequence.

If we pass the empty list or sequence, it will raise the IndexError.

Example 1: Passing a List

import random 

players_list = ['Nadal', 'Federer', 'Djokovic', 'Alcaraz', 'Sinner'] 

print(random.choice(players_list))

Output

Federer

Every time you run this code, it may select a different item, or sometimes the same item, purely by chance.

Example 2: Passing a Tuple

Passing a Tuple to random choice()

import random

num_tuple = (1, 4, 8, 3, 5)

print(random.choice(num_tuple))

Output

5

Example 3: Passing a String

Passing a String to random choice()

import random

sample_string = "Ronaldo"

print(random.choice(sample_string))

Output

d

Example 4: Using with range()

import random

random_num = random.choice(range(1, 35))

print(random_num)

Output

24

Example 5: Passing an empty sequence

import random 

empty_list = [] 

print(random.choice(empty_list))

Output

IndexError: Cannot choose from an empty sequence

Leave a Comment

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