Python Looping Modify list considerations

Source: Internet
Author: User

Python Looping Modify list considerations


Python loop list and need to modify the list elements, you should be careful not to loop the list, side modify the list, otherwise it will lead to strange and wonderful results error.


An example of a sort with a simple bubbling sort

List [12, 3, 15, 7, 45, 33, 9, 76, 40, 56] using the bubbling algorithm in order from small to large. (write only once for the sorting process, that is, to find the largest put to the last)

If written as:

Src_list = [3, 7, 9, $, 56]for (index, value) in enumerate (Src_list[:-1]): #最后一个元素不用循环if value ; Src_list[index+1]:tmp = Valuesrc_list[index] = src_list[index+1]src_list[index+1] = Tmpprint (src_list)

The following is the result of running the code above:

[3, 12, 7, 15, 33, 9, 33, 40, 76, 56]

You can see that element 33 becomes two times and element 45 is gone.


The correct way to do this is to replace the loop list with a different method, and only modify the list. Such as:

Src_list = [3], 7, 9, 1, 56]for index in xrange (Len (src_list)-+ +): #最后一个元素不用循环 if Src_list[index] > Src_list[index+1]:tmp = Src_list[index]src_list[index] = src_list[index+1]src_list[index+1] = Tmpprint (src_list)

By looping through an iterator instead of a loop list, you can access the list element in order, and then modify the list element so that it doesn't go wrong! 650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0057.gif "alt=" J_0057.gif "/>

Python Looping Modify list considerations

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.