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: