Random shuffle a 2d list and get the updated index

Hi. I am trying to shuffle a 2d list D= [[2, 2, 2, 3, 3, 2, 4, 4, 2, 4], [‘S1’, ‘S2’, ‘S3’, ‘S4’, ‘S5’, ‘S6’, ‘S7’, ‘S8’, ‘S9’, ‘S10’]] where D[0] are the values to be shuffled and D[1] is the index of the values. I want to random shuffle the D[0] and add the updated index value in the list. For example: It can be D= [[4, 4, 4, 3, 3, 2, 2, 2, 2, 2], [‘S7’, ‘S8’, ‘S10’, ‘S4’, ‘S5’, ‘S1’, ‘S2’, ‘S3’, ‘S6’, ‘S9’]]

If I do random.shuffle(D), it shuffles the D[0] and D[1] which I don’t want. If I do random.shuffle(D[0]) then it shuffles the D[0] and the index values are intact. How do I shuffle the D[0] and get the updated index values?

I don’t really understand what you want, but I notice D[0] is not shuffled in your example.

I don’t understand what you mean by “updated index values”, but… call random.shuffle on D[0] and then use the result to calculate what you’re looking for?

Sorry I updated the D[0] values. I mean that if D[0][0] shuffles and now is D[0][4], how can I also shuffle D[1][0] to D[1][4] to match the updated positions of the D[0].

It appears your data is not so much a list of a pair of lists, but, logically, a list of pairs, each of which should stay together. If you lay out the data like this, keeping what belongs together, together, it will make your life easier.

>>> transposed
[(2, 'S1'), (2, 'S2'), (2, 'S3'), (3, 'S4'), (3, 'S5'), (2, 'S6'), (4, 'S7'), (4, 'S8'), (2, 'S9'), (4, 'S10')]
>>> random.shuffle(transposed)
>>> transposed
[(4, 'S8'), (3, 'S5'), (2, 'S9'), (3, 'S4'), (2, 'S2'), (4, 'S7'), (4, 'S10'), (2, 'S3'), (2, 'S6'), (2, 'S1')]

You can always extract your original lists if you need them.

>>> [pair[0] for pair in transposed]
[4, 3, 2, 3, 2, 4, 4, 2, 2, 2]
>>> [pair[1] for pair in transposed]
['S8', 'S5', 'S9', 'S4', 'S2', 'S7', 'S10', 'S3', 'S6', 'S1']

aside: zip() can be used to transpose matrices stored as lists of lists. This leads to rather cryptic code, but it can be useful.

>>> [*map(list, zip(*transposed))]
[[4, 3, 2, 3, 2, 4, 4, 2, 2, 2], ['S8', 'S5', 'S9', 'S4', 'S2', 'S7', 'S10', 'S3', 'S6', 'S1']]