0

I'm looking for options of shortening syntax for breaking (and continuing) a loop on a condition

for _ in range(10):
    if condition:
        break
    ...

I supposed that short curcuits should work, e.g. x == 2 and break, but they cause SyntaxError.

What are Python's options for one-line conditioning, except if condition: break?

Stepan Zakharov
  • 547
  • 2
  • 11
  • 4
    if condition: break is the pythonnic way to go. I'm unsure there is other alternative. break isn't a statement that can have a value hence it can't be used in any statements requiring a value (as it doesn't even return None as all other statements) – laenNoCode Oct 22 '22 at 08:26

1 Answers1

2

You could use itertools.takewhile to combine aspects of a for and while loop, moving the (negated) break condition to the loop's head. The condition in the lambda can use both variables from the enclosing scope and the current item from the iterable.

from itertools import takewhile

for x in takewhile(lambda x: not condition, iterable):
    ...

However, while this is shorter (at least in terms of lines), I would not consider it more readable. I would just stick with the explicit break.

tobias_k
  • 81,265
  • 12
  • 120
  • 179