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.
This alternative may be useful for some applications where you want to swap the ordering function.
As you learned the in-place shuffling was the problem. I also have problem frequently, and often seem to forget how to copy a list, too. Using
sample(a, len(a))
is the solution, usinglen(a)
as the sample size. See https://docs.python.org/3.6/library/random.html#random.sample for the Python documentation.Here's a simple version using
random.sample()
that returns the shuffled result as a new list.Plan: Write out the shuffle without relying on a library to do the heavy lifting. Example: Go through the list from the beginning starting with element 0; find a new random position for it, say 6, put 0’s value in 6 and 6’s value in 0. Move on to element 1 and repeat this process, and so on through the rest of the list
It works fine. I am trying it here with functions as list objects:
It prints out: foo1 foo2 foo3 foo2 foo3 foo1 (the foos in the last row have a random order)
It took me some time to get that too. But the documentation for shuffle is very clear:
So you shouldn't
print random.shuffle(b)
. Instead dorandom.shuffle(b)
and thenprint b
.