How to Shuffle Two Lists Together in Python?

Estimated read time 1 min read

To shuffle two lists together in Python, you can use the zip function, which combines the elements of two lists into tuples, and the random module, which provides a way to generate random numbers and shuffle lists. Here’s an example of how to shuffle two lists together in Python:

import random

# Define the two lists to be shuffled
list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c', 'd', 'e']

# Shuffle the two lists together
combined = list(zip(list1, list2))
list1, list2 = zip(*combined)

# Print the shuffled lists

In this example, the zip function is used to combine the elements of the two lists list1 and list2 into tuples, which are then shuffled using the random.shuffle() function. The resulting shuffled tuples are then unpacked back into two lists using the zip function and the * operator. Finally, the shuffled lists are displayed on the console using the print() function.

When you run this code, you will see the two lists list1 and list2 shuffled together in a random order. Note that this technique can be used to shuffle any number of lists together, simply by combining them into tuples using the zip function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply