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
  • 19,499
  • 9
  • 39
  • 60
vexato
  • 15
  • 5

1 Answers1

1

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
  • 52,436
  • 15
  • 51
  • 78