How python modifies the traversal list
Editor to share with you how to modify the traversal list of python, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Modify traversal list
> odd = lambda x: bool (x% 2) > numbers = [n for n in range (10)] > for i in range (len (numbers)): If odd (numbers [I]):... Del numbers [I] # BAD: Deleting item from a list while iterating over it...Traceback (most recent call last): File "", line 2, in IndexError: list index out of range
It is a very low-level error to delete the list when traversing. No one with a little experience will commit a crime. Make changes to the above code to execute correctly:
> odd = lambda x: bool (x% 2) > numbers = [n for n in range (10)] > numbers [:] = [n for n in numbers if not odd (n)] # ahh, the beauty of it all > numbers [0,2,4,6,8] these are all the contents of the article "how python modifies the traversal list". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!