How to Randomly Select Item from List in Python? Choice() method
For randomly selecting an item from List in Python, I prefer to go with an example. It makes understanding clear.
Assume we have the following list which contains the name of some all-time greatest cricket players:
player = ['Kohli', 'Tendulkar', 'Lara', 'Ponting', 'Kallis']
So, what is the simplest way to retrieve an item at random from this list?
We are quite confused, and we want to select one random item to give our decision. We can use the random module in python which has function choice() to choose any random item from the list. And another way is by using Numpy Python module.
In this post, I will write code for the both.
1. Randomly Select Item from List in Python Using random.choice() method:
import random player = ['Kohli', 'Tendulkar', 'ABD', 'Ponting', 'Kallis'] print(random.choice(player))
2. Randomly Select Item from List in Python using Numpy module:
You can use Numpy module as well. It works fine for all Python versions.
Numpy module does not come with Python binaries, you need to install this module using the pip tool.
import numpy player = ['Kohli', 'Tendulkar', 'ABD', 'Ponting', 'Kallis'] print numpy.random.choice(player)
It will print the name of the player randomly from the list.
Numpy is one of the best modules for data science. And there are very interesting methods to explore in Numpy.
Now finding perk to make the things interesting:
It will be a very useful code; you can use it in many ways. Suppose you are a group of buddies and you want to do some task. It’s obvious no one is willing to do the job if it is tedious.
Here comes the use of this code to randomly select an item from the list in Python. Put all your buddies on the list and run
random.choice() function or use Numpy module. Before running, just take a promise to be committed with the result. 😛
Now assign your tedious task to a misfortune guy who has been chosen randomly. 😀
If you have a long list of entries and want to choose a random entry from the file, you can use CSV file format. For more detail read about CSV file and How to read CSV file in Python.