Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 442
Jeff Avatar asked Oct 28 '11 15:10

Jeff


2 Answers

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)
like image 117
Austin Marshall Avatar answered Sep 21 '22 19:09

Austin Marshall


It would be pretty simple to implement your own using random. I would write it as follows:

def shuffle(l):
    l2 = l[:]           #copy l into l2
    random.shuffle(l2)  #shuffle l2
    return l2           #return shuffled l2
like image 38
Aaron Dufour Avatar answered Sep 21 '22 19:09

Aaron Dufour