Alex Rivera | Logout

Shuffle in Python

Asked 2011-10-28T15:21:52.830
18

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)
Edit
Report

1 Answer

13

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
answered 2011-10-28T15:28:10.653

Your Answer