I need to iterate a list till a condition is satisfied. I want the most pythonic way to write this code.
for i in list:
if condition(i):
foo(i)
else:
break
I need to iterate a list till a condition is satisfied. I want the most pythonic way to write this code.
for i in list:
if condition(i):
foo(i)
else:
break
What you have is fine, but for larger loop bodies, I would use early-exit guards:
for i in list:
if not condition(i):
break
foo(i)
This has two advantages:
break is now close to the condition that it belongs to. Otherwise, when reading the code, when you see break, you'll need to go back to remember when it happens.