Shuffling a list of objects
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, using len(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.
import random
a = range(5)
b = random.sample(a, len(a))
print a, b, "two list same:", a == b
# print: [0, 1, 2, 3, 4] [2, 1, 3, 4, 0] two list same: False
# The function sample allows no duplicates.
# Result can be smaller but not larger than the input.
a = range(555)
b = random.sample(a, len(a))
print "no duplicates:", a == list(set(b))
try:
random.sample(a, len(a) + 1)
except ValueError as e:
print "Nope!", e
# print: no duplicates: True
# print: Nope! sample larger than population
The documentation for random.shuffle
states that it will
Shuffle the sequence x in place.
Don't do:
print(random.shuffle(xs)) # WRONG!
Instead, do:
random.shuffle(xs)
print(xs)
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)
# print(x) gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
Note that shuffle
works in place, and returns None
.
More generally in Python, mutable objects can be passed into functions, and when a function mutates those objects, the standard is to return None
(rather than, say, the mutated object).