We can use the random.choice() function if we want to select a random item from a list, tuple, or string. This function accepts a sequential object like a list, string, and tuple as an argument and returns a random item or element from them.
In this Python tutorial, you will learn how to use this random.choice() function and find the random element from a sequential object like a list and tuple.
What is the Python random.choice function?
random
is an inbuilt Python module used to generate random numbers and play with random data. The random module has many methods and
choice()
is one of those. We can pick a random item from a nonempty sequence object such as a list, tuple, or string with the method.
syntax of random.choice() function
random.choice(seq)
The choice function accepts only one argument
seq
(a sequential Python object). The
seq
object can be a list, tuple, or string.
return value of random.choice function
It returns a single random value from the sequential object. If the sequential object is an empty list, tuple, or string, it returns "IndexError: list index out of range " .
Examples
let's see some examples of random.choice() function.
Example 1
pick a random item from a list
import random discount_offer = ['10% off', '12% off', '14% off', '15% off'] random_pick = random.choice(discount_offer) print(f'Congratulation you won {random_pick} on your first shopping')
Output
Congratulation you won 10% off on your first shopping
Example 2
Let's see another example, and create a rolling dice using random.choice() function
import random dice = [1, 2, 3, 4, 5, 6] roll_dice = random.choice(dice) print(f'You Got: {roll_dice}')
Output
You Got: 5
How to Select a random item from the list in Python?
Suppose you have a list of random numbers and you wish to select a random number how would you do that?
In the above examples, we have already used the choice function to pick a random item from a list.
Let's see another example of selecting a random element value from a list. Let's say you have a list of top marvel movies and you could not select which one to watch today, let's write a python script that helps you to pick a random one.
import random marvel_movies = ['Black Panther','Avengers: Endgame', 'Iron Man', 'Thor: Ragnarok', 'SpiderMan: Homecoming'] #select a random movie to_watch = random.choice(marvel_movies) print("Movie to watch today is: ", to_watch)
Output
Movie to watch today is: Avengers: Endgame
How to select multiple random choices from a list?
With the
choice()
function we can only select one item from the list or any other sequential object. If we want to select multiple random items from a list, we have to run the choice function inside a loop.
Example (Select 3 random values from the list)
import random dice =list(range(1,7)) #create a list from 0 to 1 print("Diced rolled three times") #roll dice 3 times for i in range(3): dice_rolled = random.choice(dice) print(dice_rolled)
Output
Diced rolled three times 2 6 2
Using a for loop with the random.choice() function will do the trick when we want to find multiple random items from a list. But there is another approach to performing a similar task, i.e. random.choices() function.
random.choices function
With the
random.choices
function we can pick
k
number of random items from a list. This function is similar to the
choice()
function with some extra argument values.
Syntax of random.choices() function
random.choices(population, weights=None, *, cum_weights=None, k=1)
The random.choices() method can accept 4 argument values
 population: it is a sequential value and could be a list, tuple or string.

weights:
it is a list of integer values, defining the probability weightage of selecting the items. By default its value is
None
means all the items of the population have an equal probability of random selection.  cum_weights: It is also a list of integer values, defining the weightage of selecting items. But it define the possibility in accumulation. For example the weights [2,1,1] is similar to the cum_weights [2,3,4]
 k: It represents an integer number, that defines the k number of random items to select from the list or any other sequential object. It is also an optional argument value by default its value is 1, which means if it is not specified the function will return a list of a single item.
return value of random.choices function
The function returns a list with k number of random items from the population object. It also returns an IndexError if the population object is an empty list, tuple, or string.
Example
Suppose you own an ecommerce website and you want to give a gift coupon or a discount offer to k number of users. The discount offer varies from 10 to 60%, and you wish to randomly select the discount offer for these k users. And you also wish to set the probability of selecting the discount offer, which means you do not want that all of them get 60% off the discount offer.
import random discount_offer = ['10% off','20% off', '30% off', '40% off','50% off', '60% off'] #the selection probability of 10%off is 10 times higher 50 and 60 #the selection probability of 20%off is 8 times higher 50 and 60 #the selection probability of 30%off is 7 times higher 50 and 60 #the selection probability of 40%off is 6 times higher 50 and 60 #the selection probability of 50% off and 60% off is same selection_weight = [10, 8, 7, 6, 1, 1] #10 users users = 10 print(random.choices(discount_offer, weights= selection_weight, k=users))
Output
['30% off', '20% off', '10% off', '20% off', '40% off', '30% off', '20% off', '40% off', '20% off', '10% off']
How to select random multiple choices without any repetition?
Both random.choice() and random.choices() functions can be used in selecting multiple random items, but both of them can pick repetitive elements. If we want to pick multiple items without repetition we have to use the
random.sample()
function.
Syntax
random.sample(population, k, counts=None)
The sample function is similar to the choices function but here the value of k must be equal or less than the size of the population object, otherwise, we receive the "ValueError: Sample larger than population or is negative" .
Example
import random marvel_movies = ['Black Panther','Avengers: Endgame', 'Iron Man', 'Thor: Ragnarok', 'SpiderMan: Homecoming'] #select 3 random movies to_watch = random.sample(marvel_movies, k=3) print("Movies to watch today are: ", to_watch)
Output
Movies to watch today are: ['Black Panther', 'SpiderMan: Homecoming', 'Thor: Ragnarok']
How to choose a random item from a Python set?
The random.choice function can only work on sequential data objects such as list, tuple, and string. If we try to pick a random item from a list using the choice or choices functions, we will encounter the error
TypeError: 'set'
object is not subscriptable
.
If we want to select a random item from a set object we first need to convert that object into a tuple or list, using the tuple() and list() functions.
Example
import random #set of movies movies = ['Black Panther','Avengers: Endgame', 'Iron Man', 'Thor: Ragnarok', 'SpiderMan: Homecoming'] #select a random movie to_watch = random.choice(list(movies)) print("Movie to watch today is: ", to_watch)
Output
Movie to watch today is: Avengers: Endgame
How to random choice a number between a range of integers
With the Python range() function we can create a sequence of integer numbers, and to select a random number from it we can either use the choice or choices function.
Example
Let's write a script that can randomly create a 4 digit OTP.
import random otp_range = range(1000,10000) #pick a random 4 digit otp otp = random.choice(otp_range) print("Your 4 digit OTP is:", otp)
Output
Your 4 digit OTP is: 2393
How to select a random boolean value using random.choice() function?
There are only two boolean values in Python True and False. We can put these two values inside a list or tuple and randomly select any one of them using the choice function.
Example
import random #boolean vlues booleans = (True, False) #select a random boolean value print(random.choice(booleans))
Output
False
How to choose a random item from a tuple using random.choice() function?
Similar to the Python list, we can use a tuple object as an argument to the choice() function, and the function will return a random item from the tuple. If the tuple is empty the function will raise the IndexError.
Example
import random #a tuple of balls balls = ("Red Ball", "Blue Ball", "Green Ball", "Yellow Ball") #select a random colour ball from balls print(random.choice(balls))
Output
Yellow Ball
For selecting multiple random values from a tuple we can use the random module choices function.
import random #a tuple of beg beg = ("Red Ball", "Blue Ball", "Green Ball", "Yellow Ball") #select random colour balls from beg print(random.choices(beg, k=5))
Output
['Green Ball', 'Yellow Ball', 'Green Ball', 'Blue Ball', 'Blue Ball'] How to select random keyvalue pairs from a dictionary?
The choice and choices functions will only select a random value from the dictionary if all the dictionary keys form a similar structure to the index numbers. This means the dictionary key must start from 0 upto n1, as shown in the example below.
Example
import random #dictionary my_dict = { 0: 50, 1: 68, 2: 70, 3: 40 } #select random value from dictionary print(random.choice(my_dict))
Output
40
If the keys of the dictionary are not structured as index numbers or have a different data type, the choice and choices functions will return KeyError. In that case, we need to convert the dictionary into a list or tuple using the list() or tuple() function.
Example select a random pair from a dictionary
import random #dictionary balls = { 'red': 50, 'green': 68, 'blue': 70, 'yellow': 40 } #select random key from dictionary key = random.choice(list(balls)) print(f"The random value is {key}:{balls[key]}" )
Output
The random value is green:68
How to randomly select an item from a list with its index number?
The random module provides a
randrange(k)
function which return a random integer number between
0
to
k1
. We can use this function to get a random index number and using that index number we can get the item from the list. With this trick, we will have the item as well as the item's index number.
Example
import random continents = ['Asia', 'Africa', 'North America', 'South America', 'Antartica', 'Europe', 'Oceania'] #get a random index number of continents index = random.randrange(len(continents)) #print the random index number value and its item print('Index:', index, 'Item:', continents[index])
Output
Index: 0 Item: Asia
How to select a random value from multiple lists?
Suppose we have two lists
old_users
and
new_users
, and we want to select a random name from these two lists. In such cases, we first need to add both the list making it a single list, and select a random item using the choice function.
Example
import random old_names = ['Rahul', 'Raj', 'Ravi'] new_names = ['Rohan', 'Rajesh', 'Rakesh'] #add both the lists names = old_names + new_names #select a random name print(random.choice(names))
Output
Rohan
How to select a random item from a multiD array?
With the help of
numpy.random.choice(a, size=k, replace=False)
method, we can generate a list of
k
random index numbers. And the index number will be range from
0
to
a
, and a is the total number of rows present in the array.
Example
import numpy as np #it will retrun a random ndarray of integer numbers with 2 items #which range will vary from 0 to 9 (10 excluded) print(np.random.choice(10, size=2))
Output
[5 3]
Now we can use the same logic to find the random row and column value for a multidimensional array and access a random item.
Example
import numpy as np #create a numpy array array = np.array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]]) print("The Array is") print(array) #number of rows number_of_rows = array.shape[0] #select the random row and column random_row,random_column = np.random.choice(number_of_rows,size=2, replace=False) print("The random row is: ", end=" ") print(array[random_row]) print("The random item is", end=" ") print(array[random_row][random_column])
Output
The Array is [[0 1 2] [3 4 5] [6 7 8]] The random row is: [6 7 8] The random item is 6
Conclusion
As the name suggests the random module is used to play with random data in Python. This method is generally used to create random numbers, shuffle list items and pick a random item from sequential data objects.
In this tutorial, we learned how to use the Python
random.choice()
function to select the random items from different data object such as list, tuple, dictionary, and set. The choice function only returns a single random value from the sequential order, to select multiple random values, the random module also provides the choices() function.
Quick Summary of random.choice
Function  Description 
random.choice(sequence)

Return a random item from the sequence object. 
random.choices(sequence, k=4)

Return 4 random items from the sequence object. 
random.choice(range(100,999))

Return a random integer number between 100 and 999. 
np.random.choice(3, size=2)

return numpy array containing 2 integer number, range 0 to 3. 
FAQ (Python random.choice interview questions)
1. What does random.choice() function return?
Ans: It returns a random item from the sequential argument passed to it.
2. What does random.choices() function return?
Ans:
It returns a list of random items from the sequential argument specified to it. The number of random items depends on the
k
argument which default value is 1.
3. Write a python script that randomly chooses the same item from the list every time the random.choice method is called.
import random items = ['pen', 'paper', 'pencil', 'book'] for i in range(10): #seed the random number generator random.seed(3) #pick the random number using choice function print(random.choice(items))
the seed() function in the above example will save the random function state, which means it will pick the same random item again and again.
4. What will happen if we pass an empty sequential object to the choice and choices functions.
Ans.
If the sequence is an empty string, list, or tuple the choice and choices functions will return the
IndexError
.
People are also reading:
Leave a Comment on this Post