What is random.shuffle() in Python?

The built-in function random.shuffle() is used to shuffle the elements of a sequence in place. Rather than generating a new sequence, the changes are made directly to the original sequence.

Syntax

random.shuffle(x[, random])

Arguments

  1. x: this is any sequence (e.g. a list) that needs to be shuffled. x cannot be an immutable object, like a string.
  2. random: an optional argument that is set to the function random() by default. random should be any function that returns a float between 0.0 and 1.0.

Return value

The random.shuffle() function returns nothing. The shuffling is done in place on x.

Example code

import random
def sampleFtn():
return 0.3
testList1 = [1, 2, 3, 4]
print("List1 before shuffling: ", testList1)
random.shuffle(testList1)
print("List after shuffling: ", testList1)
testList2 = ["one", "two", "three", "four"]
print("List2 before shuffling: ", testList2)
random.shuffle(testList2, sampleFtn)
print("List2 after shuffling: ", testList2)
# will throw error
testStr = "Educative"
print("Error thrown since strings are immutable: ")
random.shuffle(testStr)

Explanation

In the code above, the first instance of shuffle() will produce a different result each time the code is run, as the second argument is not specified.

The second instance shuffle() has the second argument specified, so it will give the same result each time the code is run. Changing the value returned by the function will change the output.

Free Resources