python shuffle two lists in the same way

Solutions on MaxInterview for python shuffle two lists in the same way by the best coders in the world

showing results for - "python shuffle two lists in the same way"
Gabriel
06 Jun 2020
1# Example usage using random:
2import random
3# Say you want to shuffle (randomly reorder) the following lists in the
4# same way (e.g. because there's an association between the elements that
5# you want to maintain):
6your_list_1 = ['the', 'original', 'order']
7your_list_2 = [1, 2, 3]
8
9# Steps to shuffle:
10joined_lists = list(zip(your_list_1, your_list_2))
11random.shuffle(joined_lists) # Shuffle "joined_lists" in place
12your_list_1, your_list_2 = zip(*joined_lists) # Undo joining
13print(your_list_1)
14print(your_list_2)
15--> ('the', 'order', 'original') # Both lists shuffled in the same way
16--> (1, 3, 2) # Use list(your_list_2) to convert to list