In this article, we will see different techniques and libraries to select items from a list randomly.

Random module

The random the module provides several APIs for doing the random selection. To select the items from a list at random, just use the random.choice() function.

Refer to the following example for more information:

import random

my_list = [1, 2, 3, 4, 5]
random_item = random.choice(my_list)
print(random_item)

output:

3

In the above example, by using random.choice(), we randomly select and retrieve an item from the list which in this case is 3.

The above example fetches only one random element from a given list. Refer the following example on how to select more than one random element from a list.

Selecting more than one random element

If we need to select multiple items from a list without duplicates (i.e., each item can be selected only once), we can use the random.sample() function.

See the following example:

import random

my_list = [1, 2, 3, 4, 5]
random_items = random.sample(my_list, 3)
print(random_items)

Output:

[2, 4, 1]

In the above output, you can see three elements are selected from the list my_list. There are no duplicate elements present and the order of the items in the output list is also random.

Using Numpy

The numpy library provides efficient functions for random selection. This is very useful when working with large datasets or needing more advanced randomization capabilities.

Similar to the numpy.random.choice(), the function random.choice() allows us to select the items from a list randomly.

Following is an example:

import numpy as np

my_list = [1, 2, 3, 4, 5]
random_item = np.random.choice(my_list)
print(random_item)

Output

4

Categorized in:

Tagged in: