August 2018
Intermediate to advanced
332 pages
9h 12m
English
In some situations, we need to iterate over more than one dimension, looking for a value, and nested loops come as the first idea. When the value is found, we need to stop iterating, but the break keyword doesn't work entirely because we have to escape from two (or more) for loops, not just one.
What would be the solution for this? A flag signaling escape? No. Raising an exception? No, this would be the same as the flag, but even worse because we know that exceptions are not to be used for control flow logic. Moving the code to a smaller function and return it? Close, but not quite.
The answer is, whenever possible, flat the iteration to a single for loop.
This is the kind of code we would like to avoid:
def search_nested_bad(array, ...