Home > Software design >  What does Python random.shuffle()'s second argument do?
What does Python random.shuffle()'s second argument do?

Time:04-25

According to the Python Documentation,

random.shuffle(x[, random])

Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random().

Note that for even rather small len(x), the total number of permutations of x is larger than the period of most random number generators; this implies that most permutations of a long sequence can never be generated.

Even after reading this, I still don't understand what is the role of the "random" argument. Also, why on earth the argument form is (x[, random]), not (x, random)? what is that bracket and comma?

Sorry for the stupid question...

CodePudding user response:

The bracket and comma are just a standard documentation notation for saying "this parameter is optional". You wouldn't use the brackets when making the call.

The documentation seems pretty clear. You can provide your own random number function, if you want to. With shuffle, it's hard to come up with a good justification for this.

By default, this:

random.shuffle(lst)

is the same as

random.shuffle(lst, random.random)

CodePudding user response:

Checking the source code for shuffle, we can see that shuffle iterates through the list and swaps each item in the list with another random item in the list. The random function is used to get that random element with which to switch the current element.

For example, if you set random to a function that always returns 0, each element will be swapped with the first element in the list:

from random import shuffle

l = [1, 2, 3, 4, 5]
shuffle(l, lambda: 0)
print(l)
>>> [2, 3, 4, 5, 1]
  • Related