Python random.choice() method is used to randomly select an item from a sequence such as a list, tuple, or string.
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
import random
num_tuple = (1, 4, 8, 3, 5)
print(random.choice(num_tuple))
Output
5
Example 3: Passing a String
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
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.