DEV Community

Discussion on: How to break outer ones of nested loops in Python?

Collapse
 
xtofl profile image
xtofl

Most of the time when I encounter a nested loop, it can be removed completely by clarifying the intent of the author: "finding" a value that satisfies a predicate in the carthesian product of some ranges.

found = next(
  j for _, j in itertools.product(range(10), range(10))
  if j == 4
)
Enter fullscreen mode Exit fullscreen mode

This way, breaking out of the loop does not break the code reader's attention. (It may be broken by having to look up what itertools.product is :))

Collapse
 
alibahaari profile image
Ali Bahaari

Thanks!