views:

2675

answers:

2

I have a list of objects in python and I want to shuffle them. I thought I could use the random.shuffle method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?

import random

class a:
    foo = "bar"

a1 = a()
a2 = a()
b = [a1,a2]

print random.shuffle(b)

This will fail

+14  A: 

random.shuffle should work. Here's an example, where the objects are lists:

from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)

# print x  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
# of course your results will vary

Note that shuffle works in place, and returns None.

tom10
The in place part was what I was missing. Thanks
utdiscant
You're welcome. It's a common issue. `sort` and `reverse` are also done in place. All of these return None to point this out.
tom10
+2  A: 
>>> import random
>>> a = ['hi','world','cat','dog']
>>> random.shuffle(a,random.random)
>>> a
['hi', 'cat', 'dog', 'world']

It works fine for me. Make sure to set the random method.

Dan Lorenc
Still does not work for me, see my example code in the edited question.
utdiscant