JohnJ JohnJ - 1 month ago 12
Python Question

randomizing two lists and maintaining order in python

Say I have two simple lists,

a = ['Spears', "Adele", "NDubz", "Nicole", "Cristina"]
b = [1,2,3,4,5]
len(a) == len(b)


What I would like to do is randomize
a
and
b
but maintain the order. So, something like:

a = ["Adele", 'Spears', "Nicole", "Cristina", "NDubz"]
b = [2,1,4,5,3]


I am aware that I can shuffle one list using:

import random
random.shuffle(a)


But this just randomizes
a
, whereas, I would like to randomize
a
, and maintain the "randomized order" in list
b
.

Would appreciate any guidance on how this can be achieved.

Tim Tim
Answer

I'd combine the two lists together, shuffle that resulting list, then split them. This makes use of zip()

a = ["Spears", "Adele", "NDubz", "Nicole", "Cristina"]
b = [1, 2, 3, 4, 5]

combined = list(zip(a, b))
random.shuffle(combined)

a[:], b[:] = zip(*combined)