Jeff Jeff - 4 months ago 24
Python Question

Shuffle in Python

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 Source

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)