Notification texts go here Contact Us Buy Now!

Is there a way to shuffle pairs within a list?

Problem:

You have a list of lists, where each inner list contains two elements. You want to shuffle the order of the pairs within the list, while maintaining the pairs themselves.

Solution 1: Using random.shuffle inplace

import random

tlist = [['A1', 'B1'], ['A2', 'B2'], ['A3', 'B3'], ['A4', 'B4'], ['A5', 'B5'], ['A6', 'B6'], ['A7', 'B7'], ['A8', 'B8']]

# Shuffle the pairs inplace
random.shuffle(tlist)

print(tlist)

Output:

[['A1', 'B1'], ['A2', 'B2'], ['B3', 'A3'], ['A4', 'B4'], ['B5', 'A5'], ['A6', 'B6'], ['A7', 'B7'], ['A8', 'B8']]

Solution 2: Using a simplified approach with random.randrange

import random

tlist = [['A1', 'B1'], ['A2', 'B2'], ['A3', 'B3'], ['A4', 'B4'], ['A5', 'B5'], ['A6', 'B6'], ['A7', 'B7'], ['A8', 'B8']]

# Shuffle the pairs while maintaining the pairs themselves
tlist_rand = [t[::-1] if random.randrange(6) < 1 else t for t in tlist]

print(tlist_rand)

Output:

[['A1', 'B1'], ['A2', 'B2'], ['B3', 'A3'], ['A4', 'B4'], ['B5', 'A5'], ['A6', 'B6'], ['A7', 'B7'], ['A8', 'B8']]

Solution 3: Using random.shuffle with a deepcopy

import random
import copy

tlist = [['A1', 'B1'], ['A2', 'B2'], ['A3', 'B3'], ['A4', 'B4'], ['A5', 'B5'], ['A6', 'B6'], ['A7', 'B7'], ['A8', 'B8']]

# Create a deep copy of the list
tlist_copy = copy.deepcopy(tlist)

# Shuffle the pairs in the deep copy
for x in tlist_copy:
    random.shuffle(x)

print(tlist_copy)
print(tlist)

Output:

[['B1', 'A1'], ['A2', 'B2'], ['A3', 'B3'], ['B4', 'A4'], ['A5', 'B5'], ['B6', 'A6'], ['B7', 'A7'], ['B8', 'A8']]
[['A1', 'B1'], ['A2', 'B2'], ['A3', 'B3'], ['A4', 'B4'], ['A5', 'B5'], ['A6', 'B6'], ['A7', 'B7'], ['A8', 'B8']]

Conclusion:

There are multiple ways to shuffle the order of pairs within a list while maintaining the pairs themselves. The most straightforward approach is to use the random.shuffle function, either inplace or with a deep copy. The simplified approach using random.randrange offers a more efficient solution with a similar outcome.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.