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

Ad: Are you a blogger? Join our Blogging forum.








Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.