Python list edge Traversal edge modification Problem Solution: alist[:]

Source: Internet
Author: User
Tags python list

Looking at Python recently, there is a simple question: Delete the repeating elements specified in the list and discover something useful and interesting.

1. Error demonstration
alist = [1,1,2,2,3,3,2,2,1,1]for i in alist:        if i ==1:        alist.remove(1)print(alist)

Operating results: [2, 2, 3, 3, 2, 2, 1, 1]
Cause of error : Delete list element, cause the list content to change, some element position moves forward; When the For loop continues, the index continues to add one, which causes an element to be skipped.
In this example, the second "1" and the fourth "1" are skipped, but remove () removes the first element from the list, so when the third "1" appears to enter the IF statement, the second "1" is deleted.

2. Workaround one: alist[1]
alist = [1,1,2,2,3,3,2,2,1,1]for i in alist[:]:                ###    if i ==1:        alist.remove(1)print(alist)

Operating results: [2, 2, 3, 3, 2, 2]
Brief analysis : After the control statement in the for loop is changed to "for I in alist[:]", the program implements the function correctly. For this very magical alist[:], looked for a long time, have not found relevant information. Later, in the discussion with my friends, I suddenly thought of the abstract concept of "address". The error implementation of the statement "for I in Alist" of "alist", is the name of the list, similar to the array name in C, can actually be seen as a pointer to the list, the execution for loop constantly through this address to find the corresponding element, resulting in an incorrect result.
However, "for I in alist[:]", "alist[:" is to remove all elements in alist, stored in a separate and alist area, so that when the original list is modified alist, does not modify the for loop judgment logic, is actually equivalent to alist copy to a new list, using the new list for the control of the For loop.
To verify the above conjecture, it is different to see the address of alist and alist[:] with the ID () command respectively.

3. Solution Two: Define a new list
alist = [1,1,2,2,3,3,2,2,1,1]alist_new = []for i in alist:    if i!=1:        alist_new.append(i)alist = alist_newprint  (alist)

Operating results: [2, 2, 3, 3, 2, 2]
Brief Analysis : Define a new list, add values that do not meet the criteria to the new table, and after traversing the original list, overwrite the original list with the new list.
cons : New list takes up memory

4. Workaround three: Change the cycle conditions
alist = [1,1,2,2,3,3,2,2,1,1]i = 0while i<len(alist):    if alist[i]==1:        alist.pop(i)        i = i-1    i = i+1print (alist)

Operating results: [2, 2, 3, 3, 2, 2]
Brief analysis : Change the loop condition, determine whether the traversal is complete, if delete an element, the next element moves forward, at this time the loop condition I minus 1, again judge the current position, just judge the new element after moving over. Until all elements are traversed.
cons : Logic slightly more complex, more optimized

5. Workaround four: Use the while loop and the in, index () functions
alist = [1,1,2,2,3,3,2,2,1,1]while 1 in alist :    

Operating results: [2, 2, 3, 3, 2, 2]

Brief Analysis : (1) The keyword in, determines whether an element in a set, returns True/false; in the same vein, the not-in also determines whether an element is located in a collection, and returns True/false; there is a similar keyword is, Determine whether two variables are the same object, that is, the same memory space, or the same address, also has not is.
(2) Index () method, which returns the index number of the first occurrence of the element in the sequence, and an exception is reported if the element does not exist in the sequence.
(3) the pop () function is used to remove an element from the list (an index number that needs to be deleted as an input parameter, the last element is deleted by default), and the value of the element is returned.
(4) Logic: In the while condition constantly judge whether there is a target element in the list, if any, then use Index () to find the index number of the element, and the pop () delete, until the deletion clean.

6. Workaround V: Use Filter () and LABMBDA
alist = [1,1,2,2,3,3,2,2,1,1]alist = list(filter(lambda x: x!=1, alist))print (alist)

Operating results: [2, 2, 3, 3, 2, 2]
Analysis : (1) According to the requirements of the topic, is to filter the list, it is natural to think of the filter () function, with the lambda expression is simply perfect.
(2) the filter () function: Used to filter the sequence, filter out the elements that do not meet the criteria, and return a new list of eligible elements. The two parameters are received, the first is a function, the second is a sequence, each element of the sequence is passed as a parameter to the function, and then returns True or False, and finally the element that returns true is placed in the new list.
Usage: Filter (function, iterable)
(3) Lambda: Anonymous defines a simple function, which is an expression commonly used in functional programming.
Usage: lambda [arg1 [, Arg2,..... argn]]:expression
(4) Logic: Define an anonymous function with lambda, determine if the element is not "1", or return True if true, otherwise false. Filtering is performed with the filter function to achieve the filtering function of the list.

Python list edge Traversal edge modification Problem Solution: alist[:]

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.