Python deletes list elements in iterators

Source: Internet
Author: User
Tags python list

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.