5 ms·
have always wanted `break break` syntax for this kind of thing for x in a1: for y in a2: if test(y): break break # break both outer loops
by awinter-py 4y ago
have always wanted `break break` syntax for this kind of thing
for x in a1:
for y in a2:
if test(y):
break break # break both outer loops
in general, I wonder if there's a class of 'tree-like' control structures which can break multiple levels under certain circumstances
an application might be scope management parsing -- I tried to build something like this a while ago, not clear that it's better than parser-generators but it's certainly different
- tempxyz 4y agoSwift let's you declare a label, eg: "outer", in front of the outer for loop, then you can declare "break outer".
- BiteCode_dev 4y agoItertools is your friend: from itertools import product for x, y in product(a1, a2): if test(y): break Not only you get the behavior you want, but you get an easier to read code with one less level of indentation. Bonus, you can now use "else" (which most people don't know can be used with "for" and not just "if"). Why introduce a new syntax when a library does the job? A new syntax is a huge bar to pass for a language, and nested loops are rare. Itertools is a gem, and any python dev will benefit greatly from mastering it.
- rich_sasha 4y agoIt is markedly less efficient since you will test y every time for each x, as opposed to once. O(1) vs O(n)
- henrydark 4y agoSpecifically the original double loop example also has this behavior and complexity. If the loops were written as for y in a2: if cond: break for x in a1: # something then they would have O(|a2|) complexity instead of O(|a1||a2|), but then we also don't need break break