Python choose random elements

How to Randomly Select Elements from a List in Python

Selecting a random element or value from a list is a common task — be it for randomized results 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.choice() 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:

Читайте также:  File Upload

Using random.randrange()

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

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:

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 precisely 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:

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 method selects elements without replacement, i.e., it selects without duplicates and repetitions.

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

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

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:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

import random letters = ['a', 'b', 'c', 'd', 'e', 'f'] print(random.choices(letters, k=3)) 

This returns something along the lines of:

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

It can return something like:

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.

Selecting Random n Elements with No Repetition

If you’re looking to create random collections of n elements, with no repetitions, the task is seemingly more complex than the previous tasks, but in practice — it’s pretty simple.

You shuffle() the list and partition it into n parts. This ensures that no duplicate elements are added, since you’re just slicing the list, and we’ve shuffled it so the collections are random.

If you’d like to read more about splitting a list into random chunks take a look at — How to Split a List Into Even Chunks in Python.

We’ll save the result in a new list, and if there’s not enough elements to fit a final collection, it’ll simply be unfinished:

import random def select_random_Ns(lst, n): random.shuffle(lst) result = [] for i in range(0, len(lst), n): result.append(lst[i:i + n]) return result lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(select_random_Ns(lst, 2)) 

This results in a list of random pairs, without repetition:

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() .

Источник

Get Random Element from a Python List—random.choice()

To pick a random element from a list in Python, use the random module’s choice() method:

import random names = ["Alice", "Bob", "Charlie"] print(random.choice(names))

This provides you with a quick answer. However, there are other ways you can consider. Let’s take a deeper look at randomly picking elements from lists in Python.

Random Element from a List in Python

There are six different ways to select elements randomly from a list in Python:

Let’s go through each of these methods in more detail with useful examples.

1. Random.randrange()

To choose a random value between two numbers, you can use the random.randrange() function.

To utilize this to pick a random element from a list:

  • Generate a random number index between 0 and the length of the list.
  • Get an element from a list based on that index.
import random names = ["Alice", "Bob", "Charlie", "David"] random_index = random.randrange(len(names)) random_name = names[random_index] print(random_name)

2. Random.random()

The random.random() method returns a random floating-point number between 0 and 1.

Even though it is not that practical, you can use this method to pick a random element from a list.

import random names = ["Alice", "Bob", "Charlie", "David"] random_index = int(random.random() * len(names)) random_name = names[random_index] print(random_name)

3. Random.choice()

The random.choice() is the go-to method for picking items from a list at random.

import random names = ["Alice", "Bob", "Charlie", "David"] random_name = random.choice(names) print(random_name)

4. Random.randint()

To pick a random integer between two numbers, use the random.randint() method.

When it comes to picking a random element from a list, you can use random.randint() as follows:

  • Pick a random integer index between 0 and the length of the list – 1.
  • Use the randomized index to grab the corresponding element from a list.
import random names = ["Alice", "Bob", "Charlie", "David"] random_index = random.randint(0, len(names) - 1) random_name = names[random_index] print(random_name)

5. Random.sample()

Last but not least, you can use the random.sample() method to pick a group of random elements from a list.

random.sample(list, num_elements)
  • list is the group of items from where you are picking values
  • num_elements is the number of random elemens you want to sample from the list.

For example, let’s choose two random names from a group of four:

import random names = ["Alice", "Bob", "Charlie", "David"] random_names = random.sample(names, 2) print(random_names)

6. Secrets.choice()

To pick a cryptographically strong random value from a list, use the secrets.choice() method.

This method was added in Python 3.6.

import secrets names = ["Alice", "Bob", "Charlie", "David"] random_name = secrets.choice(names) print(random_name)

However, unless you really need a cryptographically secure random number generator, use the random.choice() method instead.

Conclusion

There are a lot of ways to pick random items from a list in Python.

To take home, use the random.choice() method for picking a random element from a list. The other methods work fine, but the random.choice() method is meant for exactly that.

Thanks for reading. I hope you enjoy it.

Источник

Оцените статью