0
names_friends=["Juan","Efren","Kiki", "Esmoris", "Diego", "Nando"]
for i in names_friends:
    print(i)
    names_friends.remove(i)

print(names_friends)

After run this code I got this.

Juan
Kiki
Diego
['Efren', 'Esmoris', 'Nando']

I would highly appreciate if someone could explain to me why it doesn't remove all the items of the list.Thanks

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
vexato
  • 15
  • 5

1 Answers1

2

You are changing the iterable while iterating over it. So once you delete a object from it, it may skip the next one.

If you iterate over a copy, this problem goes away, e.g.

for i in names_friends[:]:
    print(i)
    names_friends.remove(i)
rafaelc
  • 57,686
  • 15
  • 58
  • 82