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.choice()
function from the 'random' module to get a random element from a list.
The data type of returned element depends on the elements of the list.
Python list does not have any built-in method to get a random element from a list.
Getting a random number element from a list of number using random.choice() 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 (num_list = [1, 2, 3, 4, 5, 6, 7"]
) where num_list
is the list variable and [1, 2, 3, 4, 5, 6, 7"]
is the list with integer (whole number) elements.
3. Use random.choice() function to get a random integer number from the list. In the following first example, the code "random_num = random.choice(num_list)
" is used to get a random integer number from the list where the parameter 'num_list' is the list variable.
To return a number from a list using choice() function, all the elements of the list must be of number type. Accordingly, you can get float or string type element from a list.
Please take a closer look at the following example: