Python Selecting Random Item from A List
In this article you will learn about a function named choice()which is used to select random item from a listother sequence types in python. This function is provided by random module in python. Hence to work on choice() initially you need to import random module.
Method #1 : Using random.choice()
This is is the most common method to choose a random number from a list.
Example:
# using random.choice() import random # initializing list test_list = [1, 6, 9, 2, 10] # using random.choice() to # get a random number random_num = random.choice(test_list) # printing random number print ("Random number is : " + str(random_num))
Output:
Method #2 : Using random.randrange()
In this method we can specify the range for lists as 0 to its length, and get the index, and then corresponding value.
Example:
# using random.randrange import random # initializing list test_list = [1, 6, 9, 2, 10] # using random.randrange() to # get a random number rand_idx = random.randrange(len(test_list)) random_num = test_list[rand_idx] # printing random number print ("Random number is : " + str(random_num))
Output:
Method #3 : Using random.randint()
This is also used to make any number in a range. By using that number’s index we find the corresponding value. It requires 2 mandatory arguments for range.
Example:
# using random.randint() import random # initializing list test_list=[1, 6, 9, 2, 10] # using random.randint() to # get a random number rand_idx = random.randint(0, len(test_list)-1) random_num = test_list[rand_idx] # printing random number print ("Random number is : " + str(random_num))
Output:
Share: