Why does this function not remove everything I expect it to from the input list?

  loops, python

I have the following code:

names, enemies = ["John", "Skye", "Alexander", "Skye", "Tony"], ["Skye", "John"]

def remove_enemies(names, enemies):
    for name in names:
        if name in enemies:
            names.remove(name)
            
    return names
    
remove_enemies(names, enemies)

Why does the resulting names list end up as ["Alexander", "Skye", "Tony"]? I expected ["Alexander", "Tony"] instead.

Source: Python Questions

LEAVE A COMMENT