python tips: for circulation of small problems

In python, when traversing the list with for, the iterator is maintained in the index rather than a list of elements of the list. In other words, the index for loop is iterated, if you modify the list for cycle, iterative out value is an index of the location of the new list, if the index is beyond the scope of the new list, the loop terminates.

example:

def for_test1():
    x = list(range(10))
    for index, value in enumerate(x):
        print("delete:", x)
        print("index:", index, "value:", value)
        del x[index]
    print("x:", x)

if __name__ == "__main__":
    for_test1()

Output:

delete: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
index: 0 value: 0
delete: [1, 2, 3, 4, 5, 6, 7, 8, 9]
index: 1 value: 2
delete: [1, 3, 4, 5, 6, 7, 8, 9]
index: 2 value: 4
delete: [1, 3, 5, 6, 7, 8, 9]
index: 3 value: 6
delete: [1, 3, 5, 7, 8, 9]
index: 4 value: 8
x: [1, 3, 5, 7, 9]

The example above, the elements of which are deleted in the process of x to traverse the list, you can see that although the list is changed, the index is still circulating in ascending order, indicating that the index for loop iterates, then go according to the index the list of values. When the index is beyond the scope of the new list, the loop terminates.

in conclusion:

1. Try not to traverse the list in the process, modify the list

2. If you modify, remember cycle index in ascending order, the termination condition is an index over a new list range.

Guess you like

Origin www.cnblogs.com/luoheng23/p/10988025.html