+

Python | Shuffle two lists in the same order

Method: Using the operator zip () + shuffle () + *
This method performs this task in three steps ... First, the lists are concatenated using zip () . The next step is to execute shuffle with the built-in shuffle () and the last step is to unzip the lists to split the lists using the * operator.

# Python3 code to demonstrate how it works
# Shuffle two lists in the same order
# Using zip () + * operator + shuffle ()

import random

 
# initializing lists

test_list1 = [ 6 , 4 , 8 , 9 , 10 ]

test_list2 = [ 1 , 2 , 3 , 4 , 5 ]

 
# printing lists

print ( " The original list 1: " + str (test_list1) )

print ( "The original list 2: " + str (test_list2))

 
# Shuffle two lists in the same order
# Using zip () + * operator + shuffle ()

temp = list ( zip (test_list1, test_list2))

random.shuffle (temp)

res1, res2 = zip ( * temp)

 
# Print result

print ( "List 1 after shuffle:" + str ( list (res1)))

print ( "List 2 after shuffle:" + str ( list (res2)))

Output:

 The original list 1: [6, 4, 8, 9, 10] The original list 2: [1, 2, 3, 4, 5] List 1 after shuffle: [6, 10, 4, 8, 9] List 2 after shuffle: [1, 5, 2, 3, 4] 
Get Solution for free from DataCamp guru