Search code examples
pythonpython-3.xcpython

Built-in way to do immutable shuffle in Python (CPython)?


The random.shuffle() built-in shuffles in place, which is fine for many purposes. But suppose we would want to leave the original collection intact, and generate a random permutation based on the original sequence, is there a prefered way to do this in the standard library?

When I look at CPython's random.py I see an intial comment that reads:

sequences
    ---------
           pick random element
           pick random sample
           pick weighted random sample
           generate random permutation

Particularly, the last line is of interest. However, I struggle to see what method in this class achieves this.

Naturally, this is not a hard problem to solve, even for a novice Python programmer. But it would be nice to have a standard way of doing it in the standard library, and I'm sure it must exist somewhere. Perhaps someplace other than random.py?


Solution

  • According to the docs of random.shuffle(), you could use random.sample():

    To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead of shuffle().

    The same thing was analized in this post