Get the App
SLTechnology News&Howtos  ›  Development  › 

How python modifies the traversal list

Shulou Source: shulou.com Published: 2022-06-01 04:21:50 09月21日 Update

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!

Tags: Articles content low-level not much code most of the time more knowledge experience industry information information channels this is error face-to-face channel reference learning help Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology macOS Shulou Information Linux vpn