random.shuffle() function in Python


The random.shuffle() function in Python is used to shuffle a sequence (list, tuple, string) randomly. It shuffles the elements in place, which means it modifies the original sequence.

Syntax:

random.shuffle(sequence, random=None)

Parameters: - sequence: The sequence to be shuffled. - random (optional): A function that returns a random float between 0 and 1. If not provided, the default random() function from the random module is used.

Example 1: Shuffling a list

import random

my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)

Output:

[5, 2, 1, 4, 3]

Example 2: Shuffling a string

import random

my_string = "hello"
my_list = list(my_string)
random.shuffle(my_list)
shuffled_string = ''.join(my_list)
print(shuffled_string)

Output:

ohell

Note: The random.shuffle() function does not return anything. It shuffles the sequence in place.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.