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.
random.shuffle(x[, random])
x
: this is any sequence (e.g. a list) that needs to be shuffled. x
cannot be an immutable object, like a string.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
.The random.shuffle()
function returns nothing. The shuffling is done in place on x
.
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)
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.