1

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?

Christofer Ohlsson
  • 3,097
  • 4
  • 39
  • 56

2 Answers2

4

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

Ralf
  • 16,086
  • 4
  • 44
  • 68
  • Thanks. It seems to me this operation is common enough that it'd warrant its own name. But using `sample()` in this manner obviously does work. – Christofer Ohlsson Jan 16 '19 at 10:24
2

This seems like the obvious solution that shouldn't do more work than necessary:

def shuffled(gen):
    ls = list(gen)
    random.shuffle(ls)
    return ls

Since it's so simple to build from stdlib primitives, I'm not sure it would make sense to include this as a separate primitive.

djc
  • 11,603
  • 5
  • 41
  • 54