Shuffle in Python

Jeff picture Jeff · Oct 28, 2011 · Viewed 20k times · Source

Is there a straightforward way to RETURN a shuffled array in Python rather than shuffling it in place?

e.g., instead of

x = [array]
random.shuffle(x)

I'm looking for something like

y = shuffle(x)

which maintains x.

Note, I am not looking for a function, not something like:

x=[array]
y=x
random.shuffle(x)

Answer

Austin Marshall picture Austin Marshall · Oct 28, 2011

sorted with a key function that returns a random value:

import random
sorted(l, key=lambda *args: random.random())

Or

import os
sorted(l, key=os.urandom)