How to get random elements from a list in Python

Using Python 'random' module

The 'random' module is a built-in Python module that provides functions to generate random numbers.

You can use the random.sample() function from the 'random' module to get random elements from a list.

Return type of random.sample() function is list.

Python list does not have any built-in method to get random elements from a list.

Getting random elements from a list using random.sample() function

1. Import random module to use its functions using the code (import random). Here 'import' is a keyword and 'random' is the name of the module.

2. Create a list of integer (int_list = [1, 2, 3, 4, 5, 6, 7]) where int_list is the list variable and [1, 2, 3, 4, 5, 6, 7] is the list with integer (whole number) elements.

3. Use random.sample() function to get random elements from the list. In the following first example, the code "random_sample = random.sample(int_list, 1)" is used to get a list of 1 random element from the list where the parameter 'int_list' is the list variable and parameter 1 specifies the number of random elements to be returned.
You can specify the number of elements to be returned in the parameter as shown in the second example (random_sample_3 = random.sample(int_list, 3)). It returns a list of 3 random elements from the list.

Please take a closer look at the following examples:

Example of using random.choice() function

To check the output of the above example code, please try the code in Live Code Playground.

Live Code Playground

In the following Python code editor, you can practice the above code by creating more lists and apply random.sample() function. Click on the 'Execute Code' button several times to check the returned random list elements in the following Python Code Output frame. Practice until you become comfortable and proficient with your code.

Python logo Python Online Editor
Python Code Output