How to Randomly Select Item from List in Python? Choice() method
For randomly selecting 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 Python 2.x version
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.
Now finding perk to make the things interesting:
It will be 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 item from list in Python. Put all your buddies in 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.