How to shuffle elements of a list in Python

Using Python 'random' module

The 'random' module is a built-in Python module that provides function to shuffle list elements.

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

Python list does not have any built-in method to shuffle elements of a list.

Shuffling elements of a list using random.shuffle() 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, 8, 9]) where int_list is the list variable and [1, 2, 3, 4, 5, 6, 7, 8, 9] is the list with integer (whole number) elements.

3. Use random.shuffle() function to shuffle elements of the list. In the following first example, the code "random.shuffle(int_list)" is used to shuffle elements of the list where the 'int_list' is passed as the parameter of shuffle function.
In the second example, a string list elements (str_list = ["apple", "banana", "mango", "orange"]) are shuffled using random.shuffle(str_list).

Please take a closer look at the following examples:

Example of using random.shuffle() 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.shuffle() function. Click on the 'Execute Code' button several times to check the shuffled 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