Choosing from a List

Lynn Conway's challenge introduced you to Python lists (click here if you need a refresher). The random library gives us some fun ways to choose random elements from lists.

You might start off by remembering that each element of a list has an index, and generate a random number to act as the index.

>>> activities = ["snowboarding", "swimming", "running", "football", "flying"]

>>> x = random.randint(0, 4)

>>> print(activities[x])

"swimming"

>>> x = random.randint(0, 4)

>>> print(activities[x])

"flying"

>>> x = random.randint(0, 4)

>>> print(activities[x])

"snowboarding"

But there's actually an even easier way!

random.choice(example) will return a random element from a specified sequence. The variable example can be any sort of sequence, such as a string or a list. For example:

>>> fruits = ["apple", "orange", "banana"]

>>> random.choice(fruits)

"orange"

>>> random.choice(fruits)

"apple"

>>> name = "Aprille"

>>> random.choice(name)

"l"

>>> random.choice(name)

"A"

choice will return an element from whatever sequence you give it – randomly selected, with no need to worry about indexes.

If the list you pass to choice has only one value inside of it, that single value will be returned whenever it’s run.

>>> vegetable = ["tomato"]

>>> random.choice(vegetable)

"tomato"

>>> random.choice(vegetable)

"tomato"

However, the list must have at least one value inside of it. If you run choice on an empty sequence, such as random.choice([]), then you will get an error and the code will not continue.

All of these Python functions use pseudo-random number generators. It uses a particular generator called a “Mersenne Twister” - a very complex algorithm that takes in a seed to determine what number is generated. Unless you specify this seed, the random module will use the number of milliseconds that have passed since the 1st of January 1970, at midnight.

So it's almost impossible to predict what output you will get, but if you know exactly how many milliseconds have passed, you could know which numbers will be generated. This is why these functions are called pseudo random, as opposed to being truly unpredictable, but pseudo randomness is nearly always random enough for our purposes.