Tuesday, January 12, 2021

Stack Abuse: How to Randomly Select Elements From a List in Python

Introduction

Selecting a random element or value from a list is a common task - be it for randomized result from a list of recommendations or just a random prompt.

In this article, we'll take a look at how to randomly select elements from a list in Python. We'll cover the retrieval of both singular random elements, as well as retrieving multiple elements - with and without repetition.

Selecting a Random Element From Python List

The most intuitive and natural approach to solve this problem is to generate a random number that acts as an index to access an element from the list.

To implement this approach, let's look at some methods to generate random numbers in Python: random.randint() and random.randrange(). We can additionally use random.choise() and supply an iterable - which results in a random element from that iterable being returned back.

Using random.randint()

random.randint(a, b) returns a random integer between a and b inclusive.

We'll want random index in the range of 0 to len(list)-1, to get a random index of an element in the list:

import random

letters = ['a', 'b', 'c', 'd', 'e', 'f']
random_index = random.randint(0,len(letters)-1)

print(letters[random_index])

Running this code multiple times yields us:

e
c
f
a

Using random.randrange()

random.randrange(a) is another method which returns a random number n such that 0 <= n < a:

import random

letters = ['a', 'b', 'c', 'd', 'e', 'f']
random_index = random.randrange(len(letters))

print(letters[random_index])

Running this code multiple times will produce something along the lines of:

f
d
d
e

As random.randrange(len(letters)) returns a randomly generated number in the range 0 to len(letters) - 1, we use it to access an element at random in letters, just like we did in the previous approach.

This approach is a tiny bit simpler than the last, simply because we don't specify the starting point, which defaults to 0.

Using random.choice()

Now, an even better solution than the last would be to use random.choice() as this is precicely the function designed to solve this problem:

import random 

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

print(random.choice(letters))

Running this multiple times results in:

b
e
e
f
e

Selecting More Than One Random Element From Python List

Using random.sample()

The first method that we can make use of to select more than one element at random is random.sample(). It produces a sample, based on how many samples we'd like to observe:

import random 

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

print(random.sample(letters, 3))

This returns a list:

['d', 'c', 'a']

This method selects elements without replacement, i.e., it selects without duplicates and repetitions.

If we run this:

print(random.sample(letters, len(letters)))

Since it doesn't return duplicates, it'll just return our entire list in a randomized order:

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

Using random.choices()

Similar to the previous function, random.choices() returns a list of randomly selected elements from a given iterable. Though, it doesn't keep track of the selected elements, so you can get duplicate elements as well:

import random 

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

print(random.choices(letters, k=3))

This returns something along the lines of:

['e', 'f', 'f']

Also, if we run:

print(random.choices(letters, k = len(letters)))

It can return something like:

['d', 'e', 'b', 'd', 'd', 'd']

random.choices returns a k-sized list of elements selected at random with replacement.

This method can also be used implement weighted random choices which you can explore further in the official Python documentation.

Conclusion

In this article, we've explored several ways to retrieve one or multiple randomly selected elements from a List in Python.

We've accessed the list in random indices using randint() and randrange(), but also got random elements using choice() and sample().



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...