How to randomly select elements from a list in python ?


Introduction

When working with Python, you may often encounter situations where you need to select random elements from a list. This can be useful in many applications including games, statistical analysis, and machine learning.

The python programming language provides us with tools that make it easy to randomly select elements from a list. In this article, we will explore how to do this using python.

Creating a list in Python

To create a list in python, we use square brackets "[ ]" to enclose the elements of the list. For example

l = ['a','b','c','d','e','f']

Randomly select an element from a list using random.choice()

To randomly select an element from a list, you can employ the function random.choice(). This solution offers a simple and effective way to accomplish the task.

import random

random.choice(l)

For instance, the mentioned code will provide:

'c'

Creating a selection of random elements from another list

One way to generate a list of random elements is by utilizing a list comprehension

r = [random.choice(l) for i in range(2)]

For instance, here are some examples of returns.

['a', 'f']

Here's another example where 10 elements are randomly selected from a list:

r = [random.choice(l) for i in range(10)]

Output

['e', 'd', 'b', 'b', 'c', 'b', 'a', 'a', 'b', 'c']

Randomly select always the same elements

Note: To consistently obtain the same output, you can utilize a seed value:

random.seed(42)

[random.choice(l) for i in range(10)]

Output

['f', 'a', 'a', 'f', 'c', 'b', 'b', 'b', 'f', 'a']

Removing duplicate elements

To eliminate duplicate elements from your list, you can follow a simple approach. First, convert your list into a set, which automatically removes any duplicates. Then, if needed, convert the set back into a list. This process efficiently ensures that your list contains only unique elements.

l = ['a', 'a', 'a', 'b', 'c','d','e','f']

l = list(set(l))

Output

['b', 'c', 'f', 'e', 'd', 'a']

Randomly select an element from a list using random.sample()

To randomly select an element from a list, you can also use the random.sample() function. The benefit lies in generating a sample without replacement, which implies that each element is selected only once:

random.sample(l,n)

"n" denote the size of the sample (where n is less than or equal to the length of the list). For example:

l = ['a','b','c','d','e','f']

random.sample(l,2)

Output

['c', 'e']

Please note that if the value of 'n' exceeds the total number of elements in the list, an error message will be displayed: "ValueError: Sample larger than population or is negative". On the other hand, if 'n' is equal to the number of elements in the list, it is equivalent to randomly shuffling all the elements.

Randomly select an element from a list using random.shuffle()

Another approach is to randomly shuffle our list and then slice it afterwards

l = ['a','b','c','d','e','f']

random.shuffle(l)

n = 2

l[:n]

Output

['d', 'a']

Randomly select an element from a list using Numpy

One of the many functions within numpy is random.choice(), which allows us to randomly select elements from a list.
To use random.choice(), we first need to import numpy into our Python environment. We can do this by using the following code:

import numpy as np

Next, we can create a list of elements that we want to randomly select from. For example, let's say we have a list of colors:

l = ['a','b','c','d','e','f']

Now, we can use random.choice() to select a random color from this list. We simply need to pass the list as an argument in the function, like this:

np.random.choice(l)

This will return a single element from the list, chosen at random. We can also specify the number of elements we want to select by using the size parameter in the function. For example, if we want to select three random colors from our list, we can do this:

np.random.choice(l, size=3)

This will return a numpy array with three randomly selected elements from the list.

array(['c', 'e', 'c'], dtype='<U1')

Please note that the output mentioned above is an array. If you prefer a list instead:

list( np.random.choice(l, size=3) )

Output

['b', 'e', 'c']

References

Links Site
random — Generate pseudo-random numbers docs.python.org
numpy.random.choice numpy.org