The for loop is one of the most common and effective methods for traversing a list. It’s simple to read, fast, and allows us to create a lot of data quickly. However, learning different ways to traverse lists can be confusing, especially when interviewers ask questions about them.
This article addresses the question “Why is traversal with a for loop a good method for accessing and updating items?” It also discusses some of the issues that can arise when using the for loop.
For example, if you have an array that contains both rows and columns in a 2D data structure, the for loop cannot be used to search each individual row in the array because it will run forever, as shown in the following example. This is because the for loop only stops executing its body when it encounters a condition, which in this case is the Boolean expression False.
A loop that uses a foreach instead of a for loop will have no problem locating the correct value in the array. This is because foreach executes the callback function for each array element, which can be useful in determining whether or not an item is present.
In addition, the foreach function is more Pythonic, as it uses tuple unpacking. This allows you to process the keys and values separately, which gives you more control over the dictionary. For example, if you wanted to modify the value of fruits[fruit], you would use something like fruits[fruit] = round(price * 0.9, 2) instead of directly modifying price.