What is random choice() Function in Python

Selecting a random element is a repetitive task in Python, and fortunately, it supports a random module that provides functions to generate random strings, numbers, integers, and elements from a sequence.

Python random.choice

Python random.choice() is a built-in method that returns a random element from the non-empty sequence. The random.choice() method accepts a sequence which can be a  list, array, string, dictionary, tuple, or set.

To find a random element from a sequence, use the random.choice() method. You can also select a random password from a word list and a random element from the available data.

Syntax

random.choice(sequence)

Parameters

Here sequence can be a list, string, tuple, or any iterable object.

Return Value

The random choice() function returns the single element from the sequence. If we pass the empty list or sequence to the random.choice() function will raise the IndexError: Cannot choose from the empty sequence.

Example

import random

numberList = [11, 19, 21, 29, 46]
print("Random item from the list is: ", random.choice(numberList))

Output

➜  pyt python3 app.py
Random item from the list is:  11
➜  pyt python3 app.py
Random item from the list is:  46
➜  pyt python3 app.py
Random item from the list is:  19
➜  pyt python3 app.py
Random item from the list is:  29

Here, we imported the random module and then defined a list. You can see that every time we run the above program, we get a different random number from the list.

The random.choice() method picks the random item from the list every time we run the code.

Select multiple choices from the list

The random.choice() method only returns a single element from the list. To randomly select more than one element from the list or set, I recommend using the random.sample() or random.choices() instead.

import random

numberList = [11, 19, 21, 29, 46, 10, 18, 37]
print("Random item from the list is: ", random.choices(numberList, k=4))

Output

Random item from the list is:  [10, 29, 37, 46]

We want to select four random items from the list and to do that, and we have used the random.choices() method.

We have passed the list and the k=4 parameter, the sampling size that tells that we want four random items from the list.

Python random choices without repetition

Python random.sample()

The random sample() is an inbuilt function of a random module in Python that returns a specific length list of items chosen from the sequence, i.e., list, tuple, string, or set. Used for random sampling without replacement.

Use the random.sample() method when you want to choose multiple random items from a list without repetition or duplicates.

Raise Exception

If the sample size, i.e., k, is larger than the sequence size, ValueError is raised.

import random

numberList = [11, 19, 21, 29]
print("Random item from the list is: ", random.sample(numberList, k=5))

Output

Traceback (most recent call last):
  File "app.py", line 4, in <module>
    print("Random item from the list is: ", random.sample(numberList, k=5))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/random.py", line 363, in sample
    raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative

In this example, you can see that the value of k is greater than the sequence size; that is why it will raise an exception called ValueError.

Python random.choices()

Python random.choices() was added in Python 3.6 to choose n items from a list randomly, but the random.choices() function can repeat items.

The random.choices() method is mainly used to implement the weighted random choices so that we can choose items from the list with different probabilities.

The random choice from Python Dictionary

Python random.choice() method of a random module doesn’t accept a dictionary, and you need to convert a dictionary to a list before passing it to random.choice() function.

Let’s fetch the random key-value pair of dictionaries using random.choice() method.

import random

dict = {
    'hopper': 'DKH',
    'eleven': 'MBB',
    'mike': 'FW',
    'dustin': 'GM'
}

key = random.choice(list(dict))
print(f"Random key value pair from the dictionary is:- {key}: {dict[key]}")

Output

➜  pyt python3 app.py
Random key value pair from the dictionary is:- eleven: MBB
➜  pyt python3 app.py
Random key value pair from the dictionary is:- dustin: GM
➜  pyt python3 app.py
Random key value pair from the dictionary is:- mike: FW

A random choice from a tuple in Python

To get a random element from a tuple in Python, use the random.choice() function.

import random

tup = (11, 18, 19, 21, 29, 46)

num = random.choice(tup)
print(f"Random item from tuple is: ", num)

Output

➜  pyt python3 app.py
Random item from tuple is:  11
➜  pyt python3 app.py
Random item from tuple is:  29
➜  pyt python3 app.py
Random item from tuple is:  19
➜  pyt python3 app.py
Random item from tuple is:  18

First, we imported a random module, defined a tuple, and passed the tuple to the random.choice() function to get the random value from the tuple and print it on the console.

Python random choice from a set

To get the random element from a set in Python, use the random.choice() method. If we pass the set object directly to the choice function, we will get the TypeError: “set” object does not support indexing.

Using a random.choice() method, we can’t choose random items directly from the set without having to copy them into the tuple.

import random

set = {11, 18, 19, 21, 29, 46}

num = random.choice(tuple(set))
print(f"Random item from tuple is: ", num)

Output

➜  pyt python3 app.py
Random item from tuple is:  11
➜  pyt python3 app.py
Random item from tuple is:  18

Python random choice within a range of integers

Python range() generates the integer numbers between the given start integer to a stop integer.

import random

print("Randomly choose any number between the range of 1 to 21: ",
      random.choice(range(1, 21)))

Output

➜  pyt python3 app.py
Randomly choose any number between the range of 1 to 21:  14
➜  pyt python3 app.py
Randomly choose any number between the range of 1 to 21:  1
➜  pyt python3 app.py
Randomly choose any number between the range of 1 to 21:  7
➜  pyt python3 app.py
Randomly choose any number between the range of 1 to 21:  2

In this example, we have used a range() function to define the upper and lower limit of the integers and find the random number between and including the limit.

Every time we run the above program, we get a different integer, but it will not break the upper limit of the range function. This is because it always gives a random number within the limit.

Python random choice from boolean values

To choose the random boolean value from True or False, use the random.choice() function. Such a scenario is: flip a coin.

import random

res = random.choice([True, False])
print("The Random boolean value is: ")
print(res)

Output

The Random boolean value is:
True

Find a random item from a multidimensional array.

To find a random element from a multidimensional, use a numpy.random.choice() function to pick the random element from the multidimensional array.

First, we find the random row from the 2D array, and then after finding the 2D row, we fetch the random number from that row.

import numpy as np

array = np.arange(9).reshape(3, 3)
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 number from random row is")
print(np.random.choice(array[randomRow[0], :]))

Output

Printing 2D Array
[[0 1 2]
 [3 4 5]
 [6 7 8]]
Choose random row from a 2D array
[6 7 8]
Random number from random row is
7

In this example, we have used the numpy arange() function to create 0 to 8 numbers and then used the reshape() method to convert it into a 2D array and then printed the array.

Then we used the np.random.randint() method finds a random row from the 2D array and then uses the choice() function to find the random number from the row.

That is it for this tutorial.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.