Reputation: 3635
I am writing a program to randomly generate groups for the office scavenger hunt I am organizing 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 isn't working, it doesn't 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 don't 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))
Upvotes: 0
Views: 4852
Reputation: 44485
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
Upvotes: 1
Reputation: 11
It depends on the type of list. The code has the problem in line
for participant in participants:
Instead use
for participant in participants[:]:
Upvotes: 0
Reputation: 362
Although pylangs' answer will suffice, this is another approach to solve the problem:
import random
members = 3
participants=["Alex","Elsie","Elise","Kimani","Ryan","Chris","Paul"]
random.shuffle(participants)
for i in range(len(participants) // members + 1):
print('Group {} consists of:'.format(i + 1))
group = participants[i*members:i*members + members]
for participant in group:
print(participant)
Upvotes: 2