Python randomly select items or elements from list. Through this tutorial, i will show you how to randomly select item or element or n items or elements from a list in python.
How To Select Random Item From A List In Python
- Python randomly select item or element from the list
- Python randomly select multiple items or elements from the list
Python randomly select item or element from the list
You can use the python random.choice() method; that returns a random item from the non-empty sequence-like list:
- Import random in your python program.
- Then declare list of items.
- Select randomly an element from list using random.choice().
- At the last of program print result.
import random data = ["samsung", "tata", "amazon", "flipkart", "mi"] print(random.choice(data))
After executing the program, the output will be:
amazon
Python randomly select multiple items or elements from the list
You can use the random.sample() method; that returns a random items from the non-empty sequence-like list.
- Import random in your python program.
- Then declare list of items.
- Select randomly n element from list using random.select().
- At the last of program print result.
import random data = ["samsung", "tata", "amazon", "flipkart", "mi"] print(random.select(data, 2))
If you want to select 2 random elements from the list, and then you will pass 2 as the second argument, which suggests the number of elements you need in the list.
After executing the program, the output will be:
['samsung', 'flipkart']
Recommended Python Tutorials
Recommended:-Python Program to Calculate Simple Interest
Recommended:-Python Program to Find Average of n Numbers
Recommended:-Python Program to ASCII Value of Character
Recommended:-Python Program to Calculate Compound Interest
Recommended:-Python Program to Check Leap Year
Recommended:-Python Program To Print Number Pattern
Recommended:-Python Program to Print Star Pattern
Recommended:-Python Program Calculate Sum of n Numbers
Recommended:-Python Program to Reverse Numbers
Recommended:-Python Program to Find Largest of n Numbers
Recommended:-Python Program to Find Power of Number
Recommended:-Python Program to Print Prime Number From 1 to N
Recommended:-Python Program to Find Square Root of Number
Recommended:-Python Program to Find Cube of Number
Recommended:-Python Palindrome Program
Recommended:-Python Program to Count Set Bits in a Number
Recommended:-Python Program for BMI Calculation