[python] Shuffling a list of objects

I have a list of objects 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 objects or another way around this?

import random

class A:
    foo = "bar"

a1 = a()
a2 = a()
b = [a1, a2]


This will fail.

This question is related to python list random shuffle

The answer is

random.shuffle should work. Here's an example, where the objects are lists:

from random import shuffle
x = [[i] for i in range(10)]

# print(x)  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
# of course your results will vary

Note that shuffle works in place, and returns None.

Similar questions with python tag:

Similar questions with list tag:

Similar questions with random tag:

Similar questions with shuffle tag: