AppDividend
Latest Code Tutorials

Python random choice: How to Choose Random Element

The choice() method in Python returns a randomly selected element from the specified sequence.

Python random choice()

Python random choice() method returns a random element from the non-empty sequence. To find a random element from a sequence like a list, array, dictionary, tuple, or set, you can use Python random.choice() function.

We can also use it for selecting a random password from word-list, Selecting a random item 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, it will raise the IndexError: Cannot choose from the empty sequence.

Random.choice() Examples

Now let see how to use random.choice() with the example program.

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

First, we have 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.

If you have to randomly select more than one element from the list or set, then I would 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]

In this example, 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, which is sampling size that tells that we want random four 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 list before passing it to random.choice() function.

Let’s fetch the random key-value pair of dictionary 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

Python random choice from a tuple

To get the random item from a tuple, we can 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 have imported a random module and then defined a tuple and passed the tuple to the random.choice() function to get the random value from the tuple and printed it on the console.

Python random choice from a set

To get the random item from the set in Python, we can use the random.choice() method. But 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 it into the tuple.

Let see how to use the choice function to select a random item from the set.

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.

In this example, you will see how to use the random.choice() to pick the single random number from the range of integers.

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. It always gives the random number within the limit.

Python random choice from boolean values

To choose the random boolean value from True or False randomly, we can 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 item from a multidimensional array, we used 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 use the reshape() method to convert it into a 2D array and then printed the array.

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

That is it for this tutorial. Thanks for taking it.

See also

Python random number module

Numpy random shuffle()

Numpy random rand()

Numpy random randn()

Generate random permutation in Numpy

Leave A Reply

Your email address will not be published.

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