# Python How to randomly shuffles the list (List) sorting random.shuffle() method

created at 07-28-2021 views: 6

## scenes to be used¶

Shuffle the order of the list in an existing list

## Solution¶

import random

li=[5,4,3,2,1]

random.shuffle(li)

pirnt(li)
>>> [1,5,4,2,3]


## Random.shuffle source code analysis¶

def shuffle(self, x, random=None):
"""Shuffle list x in place, and return None.
Sort the list X randomly, and return None if x is an empty list

Optional argument random is a 0-argument function 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 that returns a value range of 0-1,
If random is the default None, the standard random.random() will be used.
"""

if random is None:
randbelow = self._randbelow
for 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 = int
for 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]


Note: Random in shuffle is a function, not a number

## Example of use¶

import random

def myfunction():
return 0.1

li=[5,4,3,2,1]
random.shuffle(li, myfunction)

print(li)

created at:07-28-2021