How to make a random choice from the list in Python
Make random selections from a list with Python: learn how with an example!
Random Choice from a List in Python
There are various ways to make a random choice from a list in Python. This article will demonstrate a few different methods with examples so you can decide which one works best for your purpose.
Using the Random Module
The random
module in Python provides lots of built-in methods for generating random data. One of these methods is random.choice()
. It allows you to select one item randomly from a list. Here is an example of how to use it:
import random
# list of items
items = ["apple", "orange", "banana"]
# select one item randomly
selected_item = random.choice(items)
print(selected_item) # prints "apple", "orange" or "banana"
Using the NumPy Module
The numpy
module in Python is used for scientific computing. It also has a built-in method for making random choices from a list. Here is an example of how to use it:
import numpy as np
# list of items
items = ["apple", "orange", "banana"]
# select one item randomly
selected_item = np.random.choice(items)
print(selected_item) # prints "apple", "orange" or "banana"
Using List Comprehension
List comprehension is a powerful and concise way to manipulate lists. It can also be used to make random choices from a list. Here is an example of how to do it:
# list of items
items = ["apple", "orange", "banana"]
# select one item randomly
selected_item = [item for item in items if random.random() < 0.5][0]
print(selected_item) # prints "apple", "orange" or "banana"
As you can see, there are several different ways to make a random choice from a list in Python. Depending on your needs, one method might be more suitable than the others. Hopefully, this article has given you a good overview of the different methods so you can decide which one to use.