In this tutorial, we will use three methods to select a random element from a python list, the second method is the best, you can use it in your python applications.
Import library
import random
Create a python list
list=['tom', 'good', 'lily', 'cate']
Method 1: Generate a random python list position to select a random element
rand_index = random.randint(0,len(list) -1) print(list[rand_index])
You must notice the scope of rand_index is [0, len(list)-1]. For details, you can read this tutorial.
Understand Python random.randint() Function for Beginners – Python Tutorial
Method 2: use random.choice() function to select a random element from a python list
rand_value = random.choice(list) print(rand_value)
This method is the simplest and best. We recommend it.
Method 3: Shuffle a list and select the first element
random.shuffle(list) print(list[0])
This function can change the order of elements in list, we do not recommend it.