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.
The shuffling process is "with replacement", so the occurrence of each item may change! At least when when items in your list is also list.
E.g.,
After,
The number of [0] may be 9 or 8, but not exactly 10.
It works fine for me. Make sure to set the random method.
'print func(foo)' will print the return value of 'func' when called with 'foo'. 'shuffle' however has None as its return type, as the list will be modified in place, hence it prints nothing. Workaround:
If you're more into functional programming style you might want to make the following wrapper function:
shuffle
is in place, so do not print result, which isNone
, but the list.