-2

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
Jorge Luis
  • 13
  • 3

1 Answers1

1

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:

  1. One less level of indentation. Makes it easier to follow the code.
  2. 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.
Jasmijn
  • 7,719
  • 2
  • 27
  • 42