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 string element from a list of string 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 string (str_list = ["apple", "banana", "mango", "orange"]
) where str_list
is the list variable and ["apple", "banana", "mango", "orange"]
is the list with string (text) elements.
3. Use random.choice() function to get a random string from the list. In the following first example, the code "random_str = random.choice(str_list)
" is used to get a random string from the list where the parameter 'str_list' is the list variable.
To return a string from a list using choice() function, all the elements of the list must be string type. Accordingly, you can get integer or float type element from a list.
Please take a closer look at the following example: