WhatsThePoint WhatsThePoint - 3 days ago 6
Python Question

randomly generating groups of people via values in a list

I am writing a program to randomly generate groups for the office scavenger hunt I am organising so I wrote this simple code quickly to simulate picking names out of a hat but only more fairer, but not exactly sure why it isnt working, it doesnt return all the names, for example i have entered 6 names into the list but it only returns 4 of them like this:

Group 1 consists of;
Chris
Ryan
Paul
Group 2 consists of;
Alex


I dont have much experience with removing elements from a list so it could well just be me doing it wrong. Any insight would be helpful.

import random
participants=["Alex","Elsie","Elise","Kimani","Ryan","Chris","Paul"]
group=1
membersInGroup=3

for participant in participants:
if membersInGroup==3:
print("Group {} consists of;".format(group))
membersInGroup=0
group+=1
person=random.choice(participants)
print(person)
membersInGroup+=1
participants.remove(str(person))

Answer

This issue is happening because you are mutating a list while iterating over it. There are a few options for solving this. One option that requires little modification to your existing code and thought process is to mutate a copy of the list, e.g. participants[:] makes a copy.

Using your code:

import random
participants=["Alex","Elsie","Elise","Kimani","Ryan","Chris","Paul"]
group=1
membersInGroup=3

for participant in participants[:]:               # only modification
    if membersInGroup==3:
        print("Group {} consists of;".format(group))
        membersInGroup=0
        group+=1
    person=random.choice(participants)
    print(person)
    membersInGroup+=1
    participants.remove(str(person))

Sample output:

Group 1 consists of;
Alex
Paul
Chris
Group 2 consists of;
Kimani
Elsie
Elise
Group 3 consists of;
Ryan

For deeper understanding, this StackOverflow documentation will describe your problem more deeply and offer additional solutions.

Comments