Select random value from a list-Python
The goal here is to randomly select a value from a list in Python. For example, given a list [1, 4, 5, 2, 7], we want to retrieve a single randomly chosen element, such as 5. There are several ways to achieve this, each varying in terms of simplicity, efficiency and use case. Let’s explore different approaches to accomplish this task.
Using random.choice()
random.choice() picks an element at random without any need for indexing, making it ideal for quick selections. This method is fast and widely used when you need to randomly pick one item from a collection.
[GFGTABS]
import random
a = [1, 4, 5, 2, 7]
res = random.choice(a)
print(res)
[/GFGTABS]
1
Using random.randint()
random.randint() generate a random index within the range of the list’s length, then access the element at that index. This approach gives you more control over the index and allows for indexing-based operations alongside random selection.
[GFGTABS]
import random
a = [1, 4, 5, 2, 7]
idx = random.randint(0, len(a) - 1)
res = a[idx]
print(res)
[/GFGTABS]
5
Using secrets.choice()
secrets.choice() is part of the secrets module, designed for cryptographic applications where security is important. It provides a randomly chosen element from a list using a cryptographically secure method, making it more secure than random.choice().
[GFGTABS]
import secrets
a = [1, 4, 5, 2, 7]
res = secrets.choice(a)
print(res)
[/GFGTABS]
1
Using random.sample()
random.sample() selects a specified number of unique elements from a list, even when k=1 to pick a single item. It’s useful when you need non-repeating selections. Although it’s slightly less efficient than choice() for a single item, it’s helpful when you plan to extend the functionality to multiple selections without repetition.
[GFGTABS]
import random
a = [1, 4, 5, 2, 7]
res = random.sample(a, 1)[0]
print(res)
[/GFGTABS]
7
Using numpy.random.choice()
numpy.random.choice() designed for selecting random elements from arrays or lists with advanced features, such as weighted probabilities. It’s more suited for working with large datasets or NumPy arrays and allows for options like sampling with replacement or applying a probability distribution.
[GFGTABS]
import numpy as np
a = [1, 4, 5, 2, 7]
res = np.random.choice(a)
print(res)
[/GFGTABS]
7
Related Articles: