How to select randomly elements from a list in python

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

Leave a Comment