The in-built choice()
function from the random
module randomly selects an element from a sequence, such as a list.
random.choice(seq)
seq
: the non-empty sequence from which the element is selected, such as a list, string, etc.This function returns an element from the sequence. If the sequence is empty, IndexError
is raised.
import random# picking a random element from defined listtestList = [1, 2, 3, 4]print("List: ", testList)element = random.choice(testList)print("Selected element from list: ", element)# picking a random letter from stringtestStr = "Educative"print("Str: ", testStr)element = random.choice(testStr)print("Selected element from string: ", element)# using choice() to pick a random number from a range:num = random.choice(range(0, 101))print("Random number from 0 to 100: ", num)
Note: the output will be different every time the code is run.