Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my python for loop stopping after 3 iterations?

I am trying to write a Secret Santa type of program. The function takes in a list of names as a parameter and is supposed to match each person with another person. No one can be matched with themselves, and each person can only receive and give one gift. It is a simple program so I’ll include the entire thing.

import random

Game1 = ["Alice", "Bob", "Charlie", "David", "Eve", "Frank"]

def matchPeople(players):
    needGift = players
    matches = []

    for player in players:
        def getReceiver():
            receiver = random.choice(needGift)
            if receiver == player:
                getReceiver()
            else: 
                matches.append([player, receiver])
                needGift.remove(receiver)
        getReceiver()
    print(matches)

matchPeople(Game1)

It is running as expected (I think), except it is stopping after 3 iterations. Upon running the matchPeople() function this is the outcome. I am very new to python (coming from JS), so I’m sure there is a logical explanation. However! I do not know what it is…

[['Alice', 'Charlie'], 
 ['Bob', 'David'], 
 ['Eve', 'Bob']]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your problem here is that needGift and players refer to the same object in memory – and when you remove elements from it inside your nested function, they are also removed from the player list.

The change listed bellow will make needGift a copy of the players list (by taking a "slice" starting at the begging and proceeding to the end of it – the default slice values when you suppress the indexes around the :)

change

needGift = players

to

needGift = players[:]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading