by BiteCode_dev · 4y ago · 0 comments
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.
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