Jeff
Jeff

Reputation: 12418

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)

Upvotes: 18

Views: 24043

Answers (6)

demsley
demsley

Reputation: 327

Using this as a demo elsewhere so thought it may be worth sharing:

import random

x = shuffleThis(x)


def shuffleThis(y):
    random.shuffle(y)
    return(y)
#end of Shuffle Function

Hope this is useful.

Upvotes: 0

bscan
bscan

Reputation: 3026

You could use numpy.random.permutation for either a list or array, but is the right function if you have a numpy array already. For lists with mixed types, converting to a numpy array will do type conversions.

import numpy as np
my_list = ['foo', 'bar', 'baz', 42]
print list(np.random.permutation(my_list))
# ['bar', 'baz', '42', 'foo']

Upvotes: 2

Austin Marshall
Austin Marshall

Reputation: 3107

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)

Upvotes: 20

Aaron Dufour
Aaron Dufour

Reputation: 17505

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

Upvotes: 13

minhee
minhee

Reputation: 5818

There is no function you are looking for. Just copy a list.

Upvotes: 5

FogleBird
FogleBird

Reputation: 76792

Just write your own.

import random

def shuffle(x):
    x = list(x)
    random.shuffle(x)
    return x

x = range(10)
y = shuffle(x)
print x # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print y # [2, 5, 0, 4, 9, 3, 6, 1, 7, 8]

Upvotes: 8

Related Questions