You’ll often find yourself wanting to select random items from a list in Python. Here’s a few ways you can go about doing it.
from random import randint names = ["Conor", "Esther", "Jonty", "Elwin", "Elise"] index = randint(0, len(names) - 1) print(names[index])
This method uses principles which can be applied across almost all programming languages. It’s important to understand how this works as you can apply it in pseudocode, and it gives you a decent high-level understanding of how the other methods work too.
First we must import the randint function from the random library. You will get an error if you don’t do this!
On line 2 I have declared a list which contains five strings, nothing much to see here.
On line 3, I use random.randint to generate a random number between 0 and len(names) – 1. As there are 5 items in the list, this will generate a number between 0 and 4. If you forget to subtract 1, your program may generate an index which is outside of the list, which will cause a runtime error. Don’t forget to store the result of randint inside a variable!
Finally, I simply print out the name at the selected index.
from random import choice names = ["Conor", "Esther", "Jonty", "Elwin", "Elise"] chosenName = choice(names) print(chosenName)
This method is relatively simple to understand, and in my opinion is the easiest way of picking a single, random item from a list in Python.
Similar to before, we start by importing the choice function from the random library.
On line 3, I have declared a variable called chosenName which will store the randomly selected name. This stores the result of the choice function, which returns a random item from a given list (In this case: names).
Finally, I print out the chosen name.
from random import sample names = ["Conor", "Esther", "Jonty", "Elwin", "Elise"] chosenNames = sample(names, 3) print(chosenNames)
This is a method I discovered recently, which is a great little shortcut for selecting multiple items at random from a list in Python.
As always, we start by importing the sample function from the random library.
On line 3, I have declared a variable called chosenNames which will store the list of names returned by the sample function. The sample function takes two arguments: a list of items to choose from, and the number of items you want to return. It’s worth noting that this method will not return duplicate items (Unless duplicates exist in the original list).
Finally, I print out the list of items returned.
If you’re a GCSE/A-Level student, I would recommend that you get comfortable with selecting multiple random items using a For loop to begin with, just so you’re familiar with the principles and how to represent them in pseudocode. For projects however, this is a great little party trick.
There are plenty more methods available which are covered in the Python 3 documentation. These are just a few of the most commonly used ones.