Home » Python

How to randomly select an item from a list in Python?

Python random module example: Here, we are going to learn how to randomly select an item from a list in Python?
Submitted by Sapna Deraje Radhakrishna, on December 04, 2019

Python random module provides an inbuilt method choice() has an ability to select a random item from the list and other sequences. Using the choice() method, either a single random item can be chosen or multiple items. The below set of examples illustrate the behavior of choice() method.

Syntax:

    random.choice(sequence) 

Here, sequence can be a list, set, dictionary, string or tuple.

Example 1: Choose a single item randomly from the list

>>> import random
>>> test_list = ['include_help', 'wikipedia', 'google']
>>> print(random.choice(test_list))
wikipedia
>>> print(random.choice(test_list))
google
>>> print(random.choice(test_list))
wikipedia
>>>

Example 2: Choose multiple items randomly from the list

In order to select multiple items from list, random module provides a method called choices.

>>> import random
>>> print(random.choices(test_list, k=2))
['wikipedia', 'include_help']
>>> print(random.choices(test_list, k=1))
['google']
>>> print(random.choices(test_list, k=3))
['google', 'google', 'google']
>>>


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.