1. Traverse from back to front
Start traversing forward from the last element of the list, so that the index position of the elements that have not been traversed will not be affected when deleting the elements.
Example:
my_list = [1,2,3,4,5] for i in range(len(my_list) - 1, -1, -1): if my_list[i] % 2 == 0: del my_list[i] print(my_list)
Output:
[1, 3, 5]
2. Use list comprehension to generate a new list
Another common practice is to use list comprehension to construct a new list and exclude elements that need to be deleted. Doing so will not modify the original list, avoiding the side effects of modifying while traversing.
Example:
my_list = [1,2,3,4,5] # Generate a new list and exclude even numbersmy_list = [x for x in my_list if x % 2 != 0] print(my_list )
Output:
[1, 3, 5]
3. Use the filter() function
Similar to list comprehension, you can usefilter()
Functions to filter out unnecessary elements and generate a new list.
Example:
my_list = [1,2,3,4,5] # Use filter() to filter out even numbersmy_list = list(filter(lambda x: x % 2 != 0, my_list)) print(my_list)
Output:
[1, 3, 5]
4. Use while loop and index
If finer granular control is required,while
Loops allow you to manually manage indexes. This approach is suitable for situations where you need to customize index behavior after you delete elements.
Example:
my_list = [1, 2, 3, 4, 5] i = 0 while i < len(my_list): if my_list[i] % 2 == 0: # Delete even numbers del my_list[i] else: i += 1 # Increment index only if elements are not deleted print(my_list)
Output:
[1, 3, 5]
Summarize
- traversal from back to front: Safe and effective, avoiding indexing problems caused by deleting elements.
- Use list comprehension: The filtering elements of the new list avoids the problem of modifying the original list.
-
filter()
Function: Can be used to create new lists, and the effect is similar to list comprehension. -
while
Loop and index control: When you need to precisely control the traversal process, you can usewhile
Cycle.
Generally speaking, try to avoid modifying the list when traversing the list. If elements must be deleted, it is recommended to use one of the above methods to avoid directly modifying the size of the original list.
This is the end of this article about several methods for deleting list elements while traversing Python. For more related Python, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!