How do I shuffle a list of objects? I tried random.shuffle
:
JavaScript
x
6
1
import random
2
3
b = [object(), object()]
4
5
print(random.shuffle(b))
6
But it outputs:
JavaScript
1
2
1
None
2
Advertisement
Answer
random.shuffle
should work. Here’s an example, where the objects are lists:
JavaScript
1
8
1
from random import shuffle
2
3
x = [[i] for i in range(10)]
4
shuffle(x)
5
print(x)
6
7
# print(x) gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
8
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).