Random Int—Python

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
Advertisement

One thought on “Random Int—Python”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: