Python random item from list

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.

Источник

Python: Select Random Element from a List

How to Select Random Items from a List in Python Cover Image

In this tutorial, you’ll learn how to use Python to choose a random element from a list. You’ll learn how to do this by choosing a random element from a list with substitution, without substitution, and how to replicate you results. You’ll also learn how to change the weighting of choices made.

Being able to work with random elements is an important skill to learn in Python. It has many wide applications, such as in data science and in game development. For example, if you’re building a card game, you may want to choose a card at random. Python comes with a helpful module, random , which we’ll explore in this tutorial in helping you work with random item selection.

By the end of this tutorial, you’ll have a strong understanding of how to use a number of helpful functions from the random module, including sample() , choice() , and choices() . You’ll have learned how to use these functions to modify the selection of random elements from a Python list.

The Quick Answer: Use random.choice()

Quick Answer - Python Select Random Item from List

What is the Python Random Module?

Python comes built-in with a module for working with pseudo-random numbers called random . Because it’s built into the language, we can easily import it:

The module comes with a number of helpful functions that allow us to randomly select or sample from a Python list. It also provides a seed generator which allows us to easily replicate our results time and time again, allowing is the opportunity to review results or troubleshoot any problems in our code.

Pick a Random Element from a List in Python

The simplest way to use Python to select a single random element from a list in Python is to use the random.choice() function. The function takes a single parameter – a sequence. In this case, our sequence will be a list, though we could also use a tuple.

Let’s see how we can use the method to choose a random element from a Python list:

# Choosing a random element from a Python list with random.choice() import random items = [1, 2, 3, 4, 5, 6, 7, 8, 9] random_item = random.choice(items) print(random_item) # Returns: 5

We can see here that the choice() function selects one random item from our list.

The function expects the function to be non-empty. So,what happens when we pass in an empty list? The function will raise an IndexError and the program will fail unless the error is handled.

Let’s see what this looks like:

# Raising an error when the list is empty import random items = [] random_item = random.choice(items) print(random_item) # Raises: IndexError: Cannot choose from an empty sequence

We can see here that the function raises an IndexError .

In the next section, you’ll learn how to use Python to choose a number of random elements without replacement.

Pick Random Elements from a List in Python without Replacement

In this section, you’ll learn how to use Python to select multiple random elements from a list without replacement. What does it mean to select without replacement? Sampling without replacement refers to only being able to pick a certain element a single time.

To use Python to select random elements without replacement, we can use the random.sample() function. The function accepts two parameters: the list to sample from and the number of items to sample.

Let’s see how we can use the random.sample() method to select multiple random elements from a list:

# Choosing random elements from a Python list with random.sample() import random items = [1, 2, 3, 4, 5, 6, 7, 8, 9] random_items = random.sample(items, 2) print(random_items) # Returns: [8, 4]

We can see that by passing in the value of 2 (for the keyword argument, k ) that two items are returned.

What happens if we pass in a value for k that exceeds the number of items in our list? Python will raise a ValueError . Let’s see what this looks like:

# Attempting to sample more values than possible import random items = [1, 2, 3, 4, 5, 6, 7, 8, 9] random_items = random.sample(items, 11) print(random_items) # Raises: ValueError: Sample larger than population or is negative

We can also use the random.sample() function to randomize the items in our list. We can do this by simply sampling all the items in the list.

# Using random.sample() to randomize our list import random items = [1, 2, 3, 4, 5, 6, 7, 8, 9] random_items = random.sample(items, len(items)) print(random_items) # Returns: [6, 3, 8, 2, 4, 5, 9, 7, 1]

Check out my tutorial on how to randomize Python list elements to learn more ways to accomplish this.

In the next section, you’ll learn how to use Python to pick random elements from a list with replacement.

Pick Random Elements from a List in Python with Replacement

There may also be times that you want to choose random items from a Python list with replacement. This means that an item can be chosen more than a single time. This has many useful applications, including in statistics.

In order to choose items randomly with replacement, we can use the random.choices() method. Similar to the random.sample() function, the function accepts a list and a number of elements, k . Since we can choose an item more than once, the value for k can actually exceed the number of items in the list.

Let’s see how we can select items with replacement in Python:

# Choosing random elements from a Python list with random.choices() import random items = [1, 2, 3, 4, 5, 6, 7, 8, 9] random_items = random.choices(items, k=4) print(random_items) # Returns: [9, 1, 5, 5]

We can see in the example above, that the value 5 was returned twice, even though it exists only once in our list.

Let’s see what happens when the number for k exceeds the number of items in the list:

# Choosing random elements from a Python list with random.choices() import random items = [1, 2, 3, 4, 5, 6, 7, 8, 9] random_items = random.choices(items, k=len(items) + 2) print(random_items) # Returns: [5, 3, 8, 2, 2, 1, 2, 7, 8, 7, 5]

We can see that by setting the value of k to be greater than the length of the list, that the list that gets returned is larger than our original list.

In the next section, you’ll learn how to pick random elements with given weights in a list in Python.

Pick Weighted Random Elements from a List in Python with Replacement

There may be times when you want certain items to carry more weight than other items. This means that when selecting random items, you may want some items to have a higher likelihood of being chosen.

We can change the weights of our items by passing in an array into the weights= parameter. Before diving into how this works, we can imagine that by default an array of equal weights is used. By changing the relative weights, we can specify how much more likely we want an item to be chosen.

Let’s see how we can use Python to give an item a ten times higher likelihood of being chosen than other items in a list:

# Choosing random items from a list with replacement and weights import random items = [1, 2, 3, 4] random_items = random.choices(items, k=4, weights=[10, 1, 1, 1]) print(random_items) # Returns: [1, 3, 1, 1]

Here, we’ve passed in the weights of [10, 1, 1, 1] . The weights are relative to one another, meaning that the first item in the list has a ten times higher chance of being chosen than other items.

In the next section, you’ll learn how to reproduce results when selecting random elements.

Using Random Seed to Reproduce Results when Selecting Random Elements

A very useful element in developing random results, is (ironically) the ability to reproduce results. This can help others replicate your results and can help significantly in troubleshooting your work as well.

The Python random module includes the concept of a “seed”, which generates a random number generator. This allows us to replicate results.

Let’s see how we can use the random seed() function to reproduce our results:

# Reproduce random item selection in Python import random random.seed(1) items = [1, 2, 3, 4, 5, 6, 7, 8, 9] random_items = random.choices(items, k=4) print(random_items) # Returns: [2, 8, 7, 3]

If we were to re-run this program, we would return the same values each time.

Conclusion

In this tutorial, you learned how to use Python to randomly select items from a Python list. You learned how to use the random module and its choice() , choices() , and sample() functions to select an item or items with and without replacement. You also learned how to apply weights to your sampling to give more preference to some items over others. Finally, you learned how to use the seed() function to be able to reproduce our results.

To learn more about the Python random module, check out the official documentation here.

Additional Resources

To learn more about similar topics, check out the tutorials below:

Источник

Читайте также:  Jimmy choo босоножки питон
Оцените статью