Why does random.shuffle return None? Why does random.shuffle return None? python python

Why does random.shuffle return None?


random.shuffle() changes the x list in place.

Python API methods that alter a structure in-place generally return None, not the modified data structure.

>>> x = ['foo', 'bar', 'black', 'sheep']>>> random.shuffle(x)>>> x['black', 'bar', 'sheep', 'foo']

If you wanted to create a new randomly-shuffled list based on an existing one, where the existing list is kept in order, you could use random.sample() with the full length of the input:

random.sample(x, len(x))     

You could also use sorted() with random.random() for a sorting key:

shuffled = sorted(x, key=lambda k: random.random())

but this invokes sorting (an O(N log N) operation), while sampling to the input length only takes O(N) operations (the same process as random.shuffle() is used, swapping out random values from a shrinking pool).

Demo:

>>> import random>>> x = ['foo', 'bar', 'black', 'sheep']>>> random.sample(x, len(x))['bar', 'sheep', 'black', 'foo']>>> sorted(x, key=lambda k: random.random())['sheep', 'foo', 'black', 'bar']>>> x['foo', 'bar', 'black', 'sheep']


This method works too.

import randomshuffled = random.sample(original, len(original))


According to docs:

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().

>>> x = ['foo','bar','black','sheep']>>> from random import shuffle>>> shuffle(x)>>> x['bar', 'black', 'sheep', 'foo']