pythonlist

How to remove N items from list to be excluded from further processing


The code process a list by selecting random 3 items.

import random
myList = ['TGJG78', 'Y7ITHL', 'VHZK0C', '288C13', 'W1JKEK', 
          'JQ55C9', 'M1BN3S', 'G5B3YF', 'MW1RJ9', 'CS9PZ6', 
          '9LJ3IY', 'XLAMG0', 'BGWN3L', 'SL2BSX']  #14 items in list
print("Selected :", random.choices(myList, k=3))

How to exclude those that have been selected previously until all the items in the list is completed. Basically, I want to randomly groups the items in the list. In my list, the last group will just have 2 items.

Output:

Selected : ['MW1RJ9', 'Y7ITHL', 'M1BN3S']

Solution

  • import random
    
    myList = ['TGJG78', 'Y7ITHL', 'VHZK0C', '288C13', 'W1JKEK', 
              'JQ55C9', 'M1BN3S', 'G5B3YF', 'MW1RJ9', 'CS9PZ6', 
              '9LJ3IY', 'XLAMG0', 'BGWN3L', 'SL2BSX']  #14 items in list
    
    random.shuffle(myList)
    n = 3 # group size
    
    for i in range(0,len(myList),n):
        group = myList[i:i+n]
        print(group)