Get the App
SLTechnology News&Howtos  ›  Development  › 

How python iterates with enumerate ()

Shulou Source: shulou.com Published: 2022-06-01 05:15:51 10月10日 Update

This article will explain in detail how python uses enumerate () to iterate. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Iterate using enumerate () instead of range (len ())

If we need to traverse a list and need to track the index and the current item, most people will use the range (len ()) syntax. In this case, we want to traverse a list, check to see if the current item is negative, and in this case set the value in the list to 0. Although the range (len ()) syntax works, it is better to use the built-in enumeration function. This returns the current index and current item as a tuple. Therefore, we can directly check the values here, or we can access items with indexes.

Data = [1,2,-3,-4] # weak: for i in range (len (data)): if data [I] < 0: data [I] = 0 # better: data = [1, 2,-3,-4] for idx, num in enumerate (data): if num < 0: data [idx] = 0 this is the end of the article on "how python iterates with enumerate ()" Hope that the above content can be helpful to you, so that you can learn more knowledge, if you think the article is good, please share it for more people to see.

Tags: Iteration preceding item article index more grammar check good practical lieutenant general content function form article knowledge several people reference work help related Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Huawei Shulou Tech Info Apple Docker