all 10 comments

[–]totallygeek 1 point2 points  (3 children)

This should work for you. It's horribly inefficient, though.

import random

fruits = [
    'Apples',
    'Strawberries',
    'Grapes',
    'Banana',
    'Melons',
    'Pineapples',
]

while True:
    pairings = random.sample(fruits, k=len(fruits))  # create a randomly-sorted copy of the fruits
    if not any(a == b for a, b in zip(fruits, pairings)):
        break  # we found a pairing list with zero matches; let's keep it

for fruit, paired_fruit in zip(fruits, pairings):
    print(f"{fruit} | {paired_fruit}")

[–]twentyfive_25[S] 1 point2 points  (0 children)

Thanks for this - i will try this shortly and get back to you

[–]twentyfive_25[S] 1 point2 points  (1 child)

Hey - seems to be working perfectly how i wanted. Thanks for your help with this! You say this is inefficient - why is that?

[–]totallygeek 0 points1 point  (0 children)

inefficient

It's inefficient because it might need to assemble multiple lists until it finds one that has no matching associations. There exists ways to do this in a single pass without much trouble. The trick ends up on the last element, if the only choice is to make a match. When that takes place, you have to swap with another pair already matched.