Methods often miss deletions or index out-of-bounds when deleting elements Examples are as follows:
Omission of deletion:
lst=[9,25,12,36] for i in lst: if i>10: (i) print(lst)
>>>[9, 12]
So why was 12 omitted? The principle is actually quite simple, as shown in the figure:
The list is traversed from subscript 0. When it reaches 25, 25 is deleted and a new list is returned:
Note that the original 25 corresponded to a subscript of 1, so the system would start traversing from a subscript of 2, but in the new list, the subscript of 2 becomes 36, so 12 is skipped.
Solution:
Simply determine that if an element is deleted from the list, the list should be traversed again starting from 0.
lst=[9,25,12,36] while True: for i in lst: if i>10: (i) # If an element is deleted, exit this traversal and start traversing the new list. break else: break print(lst)
>>>[9]
Indexing crosses the line:
When we traverse the list with subscripts, we get index out of bounds, as shown in the figure:
lst=[9,25,12,36] for i in range(len(lst)): # print(i) if lst[i]>10: (lst[i]) print(lst)
IndexError: list index out of range
The principle is the same, here the value of i is 0 1 2 3, when an element is deleted, the length of the new list is reduced, the index becomes 0 1 2, but i is still based on the index of the original list of values, so when i is taken to 3, the new list does not have the element, the index crosses the line.
Solution one:
lst=[25,9,12,36] j=0 for i in range(len(lst)): if lst[j]>10: # Below is an example of j taken to 0: # j = 0 when the corresponding element 25 is deleted. The practice of # continue means to determine if element j of the new list, i.e., element 0, meets the condition (lst[j]) continue # If the condition is not met at j = 0 of the new list, j+1 and then the next element is judged. j+=1 print(lst)
Solution 2 (recommended):
If you let the index traverse the list in reverse order you won't have the out-of-bounds problem.
This way, even if the length of the new list is reduced, the value of i is taken backwards, and the absence of a single element in the list has no effect on the value of i.
For example, if an element with an i of 3 is deleted, the highest index of the new list is 2 and the next value of i is exactly 2, which has no effect.
lst=[9,25,12,36] for i in range(len(lst)-1,-1,-1): # i : 3 2 1 0 if lst[i]>10: (lst[i]) print(lst)
to this article on the Python remove omitted and index out of bounds to solve the problem of this article, more related Python remove omitted and index out of bounds content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!