Home ยป Get a Random element from a List in Python

Get a Random element from a List in Python

In this example we show how to get a random element from a list using python

We will use 3 different methods to do this

random.randint(start, stop) – start and stop are required as they specify which position to start and to which position to stop.

random.choice(sequence) – sequence can be many things including a set, list, tuple, etc

random.randrange(start, stop, step) – This returns a random element from the specified range.

Example

import random #import random module
mylist=[1,2,3,4,5,6,7,8,9,10] #Intialize list with integer elements

print("Elements in list are:",mylist) #print the elements in the list

randint=random.randint(0, len(mylist)-1) #get random element using the random.int() method
randomint = mylist[randint]

randomchoice=random.choice(mylist) #get random element using the random.choice() method

randrange=random.randrange(len(mylist)) #get random element using the random.randrange() method
randomrange= mylist[randrange]

print("The random number from mylist is:",randomint) #print the random number in list
print("The random number from mylist is:",randomchoice) #print the random number in list
print("The random number from mylist is:",randomrange) #print the random number in list

When you run this you will see something like this

>>> %Run randomlist.py
Elements in list are: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The random number from mylist is: 4
The random number from mylist is: 7
The random number from mylist is: 9

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More