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
x: this is any sequence (e.g. a list) that needs to be shuffled.xcannot be an immutable object, like a string.random: an optional argument that is set to the functionrandom()by default.randomshould be any function that returns afloatbetween0.0and1.0.
Return value
The random.shuffle() function returns nothing. The shuffling is done in place on x.
Example code
import randomdef sampleFtn():return 0.3testList1 = [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 errortestStr = "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.