There are many applications in programming where we have to randomly pick an element in a list. Python has the random module which includes a randint function for this exact purpose. Here’s an example.
from random import randint if __name__ == '__main__': names = ['Bob Belcher', 'Linda Belcher', 'Gene Belcher', 'Tina Belcher', 'Lousie Belcher'] num = randint(0, len(names) - 1) # -1 because lists are 0 based print('Random number was', num) print('Name picked randomly is', names[num])
When run, this code produces the following output (which is different each time the script is ran).
Random number was 4 Name picked randomly is Lousie Belcher