I recently read this question which had a solution about labeling loops in Java.
I am wondering if such a loop-naming system exists in Python. I have been in a situation multiple times where I do need to break out of an outer for
loop from an inner for
loop. Usually, I solve this problem by putting the inner loop in a function that returns (among others) a boolean which is used as a breaking condition. But labeling loops for breaking seems a lot simpler and I would like to try that, if such functionality exists in python
Does anyone know if it does?
Nope.
Depending on what you are doing, there is good chance you can use something from itertools to flatten your nested for loops into a single for loop.
Here's a way to break out of multiple, nested blocks using a context manager:
You can use it to break out of multiple loops:
And you can even nest them:
There was a proposal to include named loops in python PEP3136, however, it was rejected with an explanation here. The rejection was mostly due to the rare number of circumstances where code readability would be improved by including this construct.
Though there are reasons to include named looped in language construct you can easily avoid it in python without loss of readability. An implementation of the referred example in python
I think you should try this. This is very pythonic, simple and readable.