Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a list containing random pairs from an original list?

I have a list:

lst = ['ab', 'cd','ef', 'gh', 'ij', 'mn', 'op', 'qr', 'st', 'uv', 'wx', 'yz']

I would like to take 2 random values from this list and put them in to a new list as pairs until the original list is empty.

For example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

new_list = [(‘ab’, ‘ef’), (‘ij’, ‘yz’) exc. ]
lst = []

How can I do this using a while and for loop?

I’ve tried using this method to generate a random pair from the list:

random_lst = random.randint(0,len(lst)-1)

However I’m not sure how to remove the values from the original lsit and then add them to the new list as pairs.

>Solution :

Try this

import random

lst = ['ab', 'cd','ef', 'gh', 'ij', 'mn', 'op', 'qr', 'st', 'uv', 'wx', 'yz']
new_list = []

for i in range(len(lst)//2):
    # Get a random index in the current list
    idx = random.randint(0,len(lst)-1)
    # Remove the respective element and store it
    element1 = lst.pop(idx)
    # Get another random index in the current list
    idx = random.randint(0,len(lst)-1)
    # Remove and store that element as well
    element2 = lst.pop(idx)
    # Create an entry (tuple) in the final list
    new_list.append((element1, element2))

print(new_list)

The output for me is [('yz', 'ij'), ('wx', 'ab'), ('st', 'cd'), ('gh', 'uv'), ('qr', 'ef'), ('op', 'mn')]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading