0

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))
Peter Badida
  • 11,310
  • 10
  • 44
  • 90
WhatsThePoint
  • 3,395
  • 8
  • 31
  • 53
  • Possible duplicate of [Difference between del, remove and pop on lists](http://stackoverflow.com/questions/11520492/difference-between-del-remove-and-pop-on-lists) – Ari Gold Nov 29 '16 at 11:59

3 Answers3

2

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)
Community
  • 1
  • 1
Mohammad
  • 362
  • 1
  • 7
  • 19
1

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
Graham
  • 7,431
  • 18
  • 59
  • 84
pylang
  • 40,867
  • 14
  • 129
  • 121
0

It depends on the type of list. The code has the problem in line

for participant in participants:

Instead use

for participant in participants[:]:

pylang
  • 40,867
  • 14
  • 129
  • 121
vaishnavi
  • 11
  • 4