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:
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')]