Function usage
random.shuffle() is used to shuffle the elements in a list. It is worth noting that using this method will not generate a new list, but just shuffle the order of the original list.
Code Examples
# shuffle() usage exampleimport randomx = [i for i in range(10)]print(x)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]random.shuffle(x)print(x)[2, 5, 4, 8, 0, 3, 7, 9, 1, 6]
Source code and comments
def shuffle(self, x, random=None):"""Shuffle list x in place, and return None.Shuffle the list in place, without generating a new list.Optional argument random is a 0-argumentfunction returning a random float in [0.0, 1.0);if it is the default None,the standard random.random will be used.The optional parameter random is a function from 0 to parameter, returning a random floating point in [0.0, 1.0);If random is the default value of None, the standard random.random() will be used."""if random is None:randbelow = self._randbelowfor i in reversed(range(1, len(x))):# pick an element in x[:i+1] with which to exchange x[i]j = randbelow(i + 1)x[i], x[j] = x[j], x[i]else:_int = intfor i in reversed(range(1, len(x))):# pick an element in x[:i+1] with which to exchange x[i]j = _int(random() * (i + 1))x[i], x[j] = x[j], x[i]
References
[1] Using random.shuffle in python
[2] Using random.shuffle() to shuffle the list order in Python