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 the
If you have multiple lists, you might want to define the permutation (the way you shuffle the list / rearrange the items in the list) first and then apply it to all lists:
import random
perm = list(range(len(list_one)))
random.shuffle(perm)
list_one = [list_one[index] for index in perm]
list_two = [list_two[index] for index in perm]
If your lists are numpy arrays, it is simpler:
import numpy as np
perm = np.random.permutation(len(list_one))
list_one = list_one[perm]
list_two = list_two[perm]
I've created the small utility package mpu which has the consistent_shuffle function:
import mpu
# Necessary if you want consistent results
import random
random.seed(8)
# Define example lists
list_one = [1,2,3]
list_two = ['a', 'b', 'c']
# Call the function
list_one, list_two = mpu.consistent_shuffle(list_one, list_two)
Note that mpu.consistent_shuffle
takes an arbitrary number of arguments. So you can also shuffle three or more lists with it.