How to get a random string 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.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:

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.choice() function. Click on the 'Execute Code' button several times to check the returned random string from the list 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