python-the risk of a variable iterative object in a for loop risk on for loop while looping mutable iterable object

Source: Internet
Author: User
Tags iterable
>>> A = [1,2,3,4,5,6]>>> for item in a: ...     A.remove (item)     ... >>> a[2, 4, 6]

Does it feel strange to see the code above? Intuitively, we just want to remove each element of queue a sequentially, in turn, and why the final result is [2,4,6]? If you have enough wit, you should guess what the reason is. For each for loop, the current time a. After the Remove (item) execution is complete, a is relatively shortened, and the element following the item complements the previously deleted position, resulting in the next element being deleted by the For loop. It can be seen that the use of a for statement presents an unpredictable risk if our iterative object is to change in the loop body.

>>> A = [1,2,3,4,5,6]>>> for item in a: ...     Print (' Index: ', A.index (item), ' Content: ', item)     ... A.remove (item)     ... Index:  0  content:1index:  1  content:3index:  2  content:5>>> a[2, 4, 6]

python-the risk of a variable iterative object in a for loop risk on for loop while looping mutable iterable object

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.