It is very dangerous to remove list elements in iterators, because iterators refer directly to the data in the list
Copy the list to the iterator, and then delete the original list is no problem.
Pos=turtle.move () for each_fish in fish[:]: if Each_fish.move () ==pos: #鱼儿被吃掉 turtle.eat () Fish.remove (each_fish) print (' There is a fish eaten ')
The bottom of the Python list is the implementation is an pyobject* array. It is inefficient to add an element each time it expands memory, so there is a pre-application memory when the element is added. Similarly, when deleting an element, it is not immediately reduced memory space, he will follow a certain strategy to reduce. And this reduction is not a good predictor.
Plus how the index is adjusted after deletion is not explicitly defined. For example, a list of length 3 you delete the 2nd so that the third subscript should be 2 or 3, etc. may cause ambiguity. If the memory reaches the desired condition at this time, the iterator is not very good at determining what the new index is.
So python disables the deletion of elements for versatility and security reasons.
Python deletes list elements in iterators