2
birds = ["turkey", "hawk", "chicken", "dove", "crow"]
bird = []
for animal in birds:
    if animal.startswith("c"):
        birds.remove(animal)
    else:
        bird.append(animal)
print (birds)
print (bird)

why the outcome of birds and bird is difference?!?!

Kenglong Wong
  • 67
  • 1
  • 5
  • 1
    What's your thoughts around it? Why dont you expect difference? – SMA Sep 17 '17 at 11:37
  • 2
    Short answer: You need `for animal in birds[:]:` Long answer: Read the docs... – cs95 Sep 17 '17 at 11:40
  • Long answer: You're effecting the list that you're iterating over with remove(), birds[:] creates a copy of the list that isn't effected by remove(), so you don't skip `dove` in your loop. You should use list comprehension. – foxyblue Sep 17 '17 at 11:42
  • that's because in this way one item removed from that array and all of them won't be iterated. – sajad abbasi Sep 17 '17 at 11:43

0 Answers0