HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

Shuffling a list of objects

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
shufflingobjectslist

Problem

How do I shuffle a list of objects? I tried random.shuffle:

import random

b = [object(), object()]

print(random.shuffle(b))


But it outputs:

None

Solution

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).

Code Snippets

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]]

Context

Stack Overflow Q#976882, score: 1515

Revisions (0)

No revisions yet.