In this tutorial, you’ll learn how to use Python to choose a random element from a list. You’ll learn how to do this by choosing a random element from a list with substitution, without substitution, and how to replicate you results. You’ll also learn how to change the weighting of choices made.
Being able to work with random elements is an important skill to learn in Python. It has many wide applications, such as in data science and in game development. For example, if you’re building a card game, you may want to choose a card at random. Python comes with a helpful module, random
, which we’ll explore in this tutorial in helping you work with random item selection.
By the end of this tutorial, you’ll have a strong understanding of how to use a number of helpful functions from the random module, including sample()
, choice()
, and choices()
. You’ll have learned how to use these functions to modify the selection of random elements from a Python list.
The Quick Answer: Use random.choice()
Table of Contents
What is the Python Random Module?
Python comes built-in with a module for working with pseudo-random numbers called random
. Because it’s built into the language, we can easily import it:
import random
The module comes with a number of helpful functions that allow us to randomly select or sample from a Python list. It also provides a seed generator which allows us to easily replicate our results time and time again, allowing is the opportunity to review results or troubleshoot any problems in our code.
Pick a Random Element from a List in Python
The simplest way to use Python to select a single random element from a list in Python is to use the random.choice()
function. The function takes a single parameter – a sequence. In this case, our sequence will be a list, though we could also use a tuple.
Let’s see how we can use the method to choose a random element from a Python list:
# Choosing a random element from a Python list with random.choice()
import random
items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
random_item = random.choice(items)
print(random_item)
# Returns: 5
We can see here that the choice()
function selects one random item from our list.
The function expects the function to be non-empty. So,what happens when we pass in an empty list? The function will raise an IndexError
and the program will fail unless the error is handled.
Let’s see what this looks like:
# Raising an error when the list is empty
import random
items = []
random_item = random.choice(items)
print(random_item)
# Raises: IndexError: Cannot choose from an empty sequence
We can see here that the function raises an IndexError
.
In the next section, you’ll learn how to use Python to choose a number of random elements without replacement.
Pick Random Elements from a List in Python without Replacement
In this section, you’ll learn how to use Python to select multiple random elements from a list without replacement. What does it mean to select without replacement? Sampling without replacement refers to only being able to pick a certain element a single time.
To use Python to select random elements without replacement, we can use the random.sample()
function. The function accepts two parameters: the list to sample from and the number of items to sample.
Let’s see how we can use the random.sample()
method to select multiple random elements from a list:
# Choosing random elements from a Python list with random.sample()
import random
items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
random_items = random.sample(items, 2)
print(random_items)
# Returns: [8, 4]
We can see that by passing in the value of 2 (for the keyword argument, k
) that two items are returned.
What happens if we pass in a value for k
that exceeds the number of items in our list? Python will raise a ValueError
. Let’s see what this looks like:
# Attempting to sample more values than possible
import random
items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
random_items = random.sample(items, 11)
print(random_items)
# Raises: ValueError: Sample larger than population or is negative
We can also use the random.sample()
function to randomize the items in our list. We can do this by simply sampling all the items in the list.
# Using random.sample() to randomize our list
import random
items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
random_items = random.sample(items, len(items))
print(random_items)
# Returns: [6, 3, 8, 2, 4, 5, 9, 7, 1]
Check out my tutorial on how to randomize Python list elements to learn more ways to accomplish this.
In the next section, you’ll learn how to use Python to pick random elements from a list with replacement.
Pick Random Elements from a List in Python with Replacement
There may also be times that you want to choose random items from a Python list with replacement. This means that an item can be chosen more than a single time. This has many useful applications, including in statistics.
In order to choose items randomly with replacement, we can use the random.choices()
method. Similar to the random.sample()
function, the function accepts a list and a number of elements, k
. Since we can choose an item more than once, the value for k can actually exceed the number of items in the list.
Let’s see how we can select items with replacement in Python:
# Choosing random elements from a Python list with random.choices()
import random
items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
random_items = random.choices(items, k=4)
print(random_items)
# Returns: [9, 1, 5, 5]
We can see in the example above, that the value 5 was returned twice, even though it exists only once in our list.
Let’s see what happens when the number for k exceeds the number of items in the list:
# Choosing random elements from a Python list with random.choices()
import random
items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
random_items = random.choices(items, k=len(items) + 2)
print(random_items)
# Returns: [5, 3, 8, 2, 2, 1, 2, 7, 8, 7, 5]
We can see that by setting the value of k to be greater than the length of the list, that the list that gets returned is larger than our original list.
In the next section, you’ll learn how to pick random elements with given weights in a list in Python.
Pick Weighted Random Elements from a List in Python with Replacement
There may be times when you want certain items to carry more weight than other items. This means that when selecting random items, you may want some items to have a higher likelihood of being chosen.
We can change the weights of our items by passing in an array into the weights=
parameter. Before diving into how this works, we can imagine that by default an array of equal weights is used. By changing the relative weights, we can specify how much more likely we want an item to be chosen.
Let’s see how we can use Python to give an item a ten times higher likelihood of being chosen than other items in a list:
# Choosing random items from a list with replacement and weights
import random
items = [1, 2, 3, 4]
random_items = random.choices(items, k=4, weights=[10, 1, 1, 1])
print(random_items)
# Returns: [1, 3, 1, 1]
Here, we’ve passed in the weights of [10, 1, 1, 1]
. The weights are relative to one another, meaning that the first item in the list has a ten times higher chance of being chosen than other items.
In the next section, you’ll learn how to reproduce results when selecting random elements.
Using Random Seed to Reproduce Results when Selecting Random Elements
A very useful element in developing random results, is (ironically) the ability to reproduce results. This can help others replicate your results and can help significantly in troubleshooting your work as well.
The Python random module includes the concept of a “seed”, which generates a random number generator. This allows us to replicate results.
Let’s see how we can use the random seed()
function to reproduce our results:
# Reproduce random item selection in Python
import random
random.seed(1)
items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
random_items = random.choices(items, k=4)
print(random_items)
# Returns: [2, 8, 7, 3]
If we were to re-run this program, we would return the same values each time.
Conclusion
In this tutorial, you learned how to use Python to randomly select items from a Python list. You learned how to use the random
module and its choice()
, choices()
, and sample()
functions to select an item or items with and without replacement. You also learned how to apply weights to your sampling to give more preference to some items over others. Finally, you learned how to use the seed()
function to be able to reproduce our results.
To learn more about the Python random
module, check out the official documentation here.
Additional Resources
To learn more about similar topics, check out the tutorials below: