Python provides a straightforward and efficient way to select a random item from a list and other sequence types using the built-in random module. In this article, we’ll explore different approaches to choose a random element from a list in Python.
Table of contents
- random.choice() function to Select a Random Element from a List in Python
- random.randint() and indexing to choose random element from list
- Select multiple random choices from a list
- Random choices without repetition
- A random choice from a Python set
- Random choice within a range of integers
- Get a random boolean in using random.choice()
- Random choice from a tuple
- Random choice from dictionary
- Randomly choose an item from a list along with its index position
- Choose a random element from multiple lists with equal probability
- Choose a random element from a multidimensional array
- Secure random choice
- Randomly choose the same element from the list every time
- Randomly choose an object from the List of Custom Class Objects
- Next Steps
random.choice()
function to Select a Random Element from a List in Python
Use the random.choice()
function to choose a random element from a list in Python. For example, we can use it to select a random name from a list of names.
Below are the steps and examples to choose a random item from a list.
- Import the random module: This module implements pseudo-random number generators for various distributions. See documentation. The random module in Python offers a handy
choice()
function that simplifies the process of randomly selecting an item from a list. By importing the random module, you can directly call therandom.choice()
. - Use the
random.choice()
method: Thechoice()
function takes one argument: the no-empty sequence like a list, tuple, string, or any iterable like range. Pass your list as an argument, and It will return a random element from it.
Note: The choice()
function returns a random element from the non-empty sequence. (A sequence can be a list, string, or tuple.) If the list or sequence is empty will raise IndexError (cannot choose from an empty sequence).
Now, Let’s assume you have the following list of movies. This list contains five movies. Let’s see how to choose a random movie name from it.
movie_list = ['The Godfather', 'The Wizard of Oz', 'Citizen Kane', 'The Shawshank Redemption', 'Pulp Fiction']
Example: Choose a random item from a list
import random
movie_list = ['The Godfather', 'The Wizard of Oz', 'Citizen Kane', 'The Shawshank Redemption', 'Pulp Fiction']
# pick a random element from a list of strings.
movie = random.choice(movie_list)
print(movie)
Output:
The Godfather
As you can see, this code used the random
module and the choice()
function to choose a random element, “The Godfather” from the list.
Also, you can use the following variations of random.choice()
functions to generate a random item from a sequence. We will see each one of them with examples.
Function | Description |
---|---|
random.choice(list) | Choose a random item from a sequence. Here seq can be a list, tuple, string, or any iterable like range. |
random.choices(list, k=3) | Choose multiple random items from a list, set, or any data structure. |
random.choice(range(10, 101)) | Pick a single random number from range 1 to 100 |
random.getrandbits(1) | Returns a random boolean |
random.choice(list(dict1)) | Choose a random key from a dictionary |
np.random.choice() | Return random choice from a multidimensional array |
secrets.choice(list1) | Choose a random item from the list securely |
Now, let’s learn the other ways to generate a random element from a list in the subsequent section of the article.
random.randint()
and indexing to choose random element from list
Another approach to selecting a random element from a list involves using the randint() function from the random module to generate a random index within the range of the list. By using this index, you can access and retrieve the corresponding element from the list.
The random.randint()
function takes two arguments: the minimum and maximum values, and it returns a random integer between those two values.
Example:
import random
num_list = [10, 15, 20, 25, 30]
random_index = random.randint(0, len(my_list) - 1)
random_element = my_list[random_index]
print('Random Number:', random_element)
Output:
Random Number: 20
Select multiple random choices from a list
The random.choice()
function chooses only a single element from a list. If you want to select more than one item from a list or set, use the random sample() or choices()
functions instead.
random.choices(population, weights=None, *, cum_weights=None, k=1)
- The
random.choices()
method was introduced in Python version 3.6, and it can repeat the elements. It is a random sample with a replacement. - Using the
random.choices(k)
method, we can specify the sampling size. Herek
is the number of elements to select from a list.
Example: Choose three random elements from a list
import random
# sampling with replacement
original_list = [20, 30, 40, 50, 60, 70, 80]
# k = number of items to select
sample_list = random.choices(original_list, k=3)
print(sample_list)
# Output [60, 20, 60]
As you can see, this code used the random.choices()
with 3 sampling size (the total number of items to select randomly). We got a few repeated numbers in the output because the choices()
function can repeat elements.
Random choices without repetition
Use the random.sample() function when you want to choose multiple random items from a list without repetition or duplicates.
There is a difference between choice()
and choices()
.
- The
choices()
was added in Python 3.6 to choosen
elements from the list randomly, but this function can repeat items. - The
choices()
function is mainly used to implement weighted random choices to choose multiple elements from the list with different probabilities.
Also, don’t forget to solve our Python random data generation exercise.
A random choice from a Python set
Python Set is an unordered collection of items. If we pass the set
object directly to the choice function, we will get the TypeError ('set' object does not support indexing
).
So we can’t choose random items directly from a set without copying them into a tuple.
To choose a random item from a set, first, copy it into a tuple and then pass the tuple to the choice()
function
import random
sample_set = {20, 35, 45, 65, 82}
item = random.choice(tuple(sample_set))
# random item from set
print(item)
# Output 65
Random choice within a range of integers
Python range() generates the integer numbers between the given start integer to the stop integer. In this example, we will see how to use the choice() to pick a single random number from a range of integers.
Example:
import random
# Choose randomly number from range of 10 to 100
num = random.choice(range(10, 101))
print(num)
# Output 93
Get a random boolean in using random.choice()
In Python, boolean values are either True or False. Such as flip a coin to select either coin head and tail randomly. Let’s see how to choose a random boolean value, either True or False
Example:
import random
res = random.choice([True, False])
print(res)
# Output True
Also, you can use the random.getrandbits()
to generate random Boolean in Python fastly and efficiently.
Example:
import random
# get random boolean
res = random.getrandbits(1)
print(bool(res))
# Output False
Random choice from a tuple
Same as the list, we can choose a random item out of a tuple using the random.choice()
.
import random
atuple = (20, 30, 4)
# Random choice from a tuple
num = random.choice(atuple)
print(num)
# Output 30
Random choice from dictionary
A dictionary is an unordered collection of unique values stored in (Key-Value) pairs. Let’s see how to use the choice()
function to select random key-value pair from a Python dictionary.
Note: The choice()
function of a random module doesn’t accept a dictionary. We need to convert a dictionary (dict
) into a list
before passing it to the choice()
function.
import random
weight_dict = {
"Kelly": 50,
"Red": 68,
"Scott": 70,
"Emma": 40
}
# random key
key = random.choice(list(weight_dict))
# fetch value using key name
print("Random key-value pair is ", key, ":", weight_dict[key])
# Output Random key-value pair is Red : 68
Randomly choose an item from a list along with its index position
We often need an item’s index position along with its value. You can accomplish this using a randrange() function. So let’s see how to randomly choose an item from a list along with its index position.
from random import randrange
movie_list = ['The Godfather', 'The Wizard of Oz', 'Citizen Kane', 'The Shawshank Redemption', 'Pulp Fiction']
# get random index number
i = randrange(len(movie_list))
item = movie_list[i]
# Select item using index number
print("Randomly selected item", movie_list[i], "is present at index:", i)
# Output Randomly selected item Citizen Kane is present at index: 2
Choose a random element from multiple lists with equal probability
Equal probability means each item from all lists has a fair chance of being selected randomly.
After the introduction of choices()
in Python 3.6, it is now easy to generate random choices from multiple lists without needing to concatenate them. Let’s see how to choose items randomly from two lists.
See Weighted random choice for more detail.
import random
list_one = ["Thomas", "Liam", "William"]
list_two = ["Emma", "Olivia", "Isabella"]
seqs = list_one, list_two
# Random item from two lists
item = random.choice(random.choices(seqs, weights=map(len, seqs))[0])
print(item)
# Output William
Choose a random element from a multidimensional array
Most of the time, we work with 2d or 3d arrays in Python.
- Use the
numpy.random.choice()
function to generate random choices and samples from a NumPy multidimensional array. - Using this function, we can get single or multiple random numbers from the n-dimensional array with or without replacement.
A random choice from a 2d array
import numpy as np
array = np.array([[11, 22, 33], [44, 55, 66], [77, 88, 99]])
print("Printing 2D Array")
print(array)
print("Choose random row from a 2D array")
randomRow = np.random.randint(3, size=1)
print(array[randomRow[0], :])
print("Random item from random row is")
print(np.random.choice(array[randomRow[0], :]))
Output:
Printing 2D Array [[11 22 33] [44 55 66] [77 88 99]] Choose random row from a 2D array [44 55 66] Random number from random row is 66
Random choice from 1-D array
import numpy as np
array = [10, 20, 30, 40, 50, 20, 40]
x = np.random.choice(array, size=1)
print("single random choice from 1-D array", x)
items = np.random.choice(array, size=3, replace=False)
print("multiple random choice from numpy 1-D array without replacement ", items)
choices = np.random.choice(array, size=3, replace=True)
print("multiple random choices from numpy 1-D array with replacement ", choices)
Output
single random choice from 1-D array [40] multiple random choice from numpy 1-D array without replacement [10 20 40] multiple random choices from numpy 1-D array with replacement [20 30 20]
Secure random choice
Note: Above all, examples are not cryptographically secure. If you are using it to pick a random item inside any security-sensitive application, then secure your random generator and use random.SystemRandom().choice()
instead of random.choice()
.
import random
movie_list = ['The Godfather', 'The Wizard of Oz', 'Citizen Kane', 'The Shawshank Redemption', 'Pulp Fiction']
# secure random generator
secure_random = random.SystemRandom()
item = secure_random.choice(movie_list)
print (item)
# Output 'The Godfather'
Randomly choose the same element from the list every time
Choosing the same element out of a list is possible. We need to use the random.seed()
and random.choice()
function to produce the same item every time. Let’s see this with an example.
import random
float_list = [22.5, 45.5, 88.5, 92.5, 55.4]
for i in range(5):
# seed the random number generator
random.seed(4)
# print random item
print(random.choice(float_list))
Output:
45.5 45.5 45.5 45.5 45.5
To randomly get the same choice from the list, you need to find the exact seed root number.
Randomly choose an object from the List of Custom Class Objects
For example, you have a list of objects and want to select a single object from the list. A list of objects is nothing but a list of user-defined class objects. Let’s see how to choose a random object from the List of Custom class objects.
import random
# custom class
class studentData:
def __init__(self, name, age):
self.name = name
self.age = age
jhon = studentData("John", 18)
emma = studentData("Emma", 19)
object_list = [jhon, emma]
# pick list index randomly using randint()
i = random.randint(0, len(object_list) - 1)
# Randomly select object from the given list of custom class objects
obj = object_list[i]
print(obj.name, obj.age)
# Output John 18
Next Steps
I want to hear from you. What do you think of this article? Or maybe I missed one of the usages of random.choice()
. Either way, let me know by leaving a comment below.
Also, try to solve the following Free exercise and a quiz to better understand working with random data in Python.
- Python random data generation Exercise to practice and master the random data generation techniques in Python.
- Python random data generation Quiz to test your random data generation concepts.
Reference: Python documentation on random choice.