What's the Pythonic (2.7, 3) way to write a for-loop with a condition for stopping early?
For example
for item in lst:
if not condition(item):
break
process(item)
Your way looks great! I would normally write:
for i in lst:
if i > k:
break
process(i)
(no need for explicit indexing). Or if you're feeling peckish:
map(process, it.takewhile(lambda i: i < k, lst))
You can use itertools.takewhile:
from itertools import takewhile
for item in takewhile(condition, lst):
process(item)
From the documentation:
itertools.takewhile(predicate, iterable)Make an iterator that returns elements from the iterable as long as the predicate is true.
To find your common prefix, for example:
def common_prefix(s1, s2):
return "".join(a for a, _ in takewhile(lambda t: t[0] == t[1], zip(s1, s2)))
[] on the list comprehension.return s1[:len(list(itertools.takewhile(operator.eq, s1, s2)))], though takewhile unfortunately doesn't take multiple iterables. I'll have to read up on argument expansion.print ' '.join(a for a in xrange(3) if a < 4) throw a TypeError ?lambda (a,b):, and lambda pair: pair[0] == pair[1] in Python 3?Default answer: the way it's already written.
for item in lst:
if not condition(item):
break
process(item)
n = len(lst); iterate over lst directly or enumerate it if you actually need the index.n may have been precalculated as a bound. I didn't mean for the question to be about an actual list, though that's my fault.for index, item in enumerate(whatever): if index > bound or condition(item): break; process(item). This won't break if len(whatever) < bound.There have been attempts to establish a new syntax for list comprehension that incorporates the idea of takewhile.
In that format, the code can be written as [terrible way of list comprehension as one-line iteration without value, which will not be given in the answer itself for fear of collateral damage in impressionable minds].
For the problem of "common prefix of two strings", we have something like this:
def commonprefix(s1, s2):
return ''.join(x for x, y in zip(s1, s2) while x==y)
Unfortunately, it seems that these attempts haven't been able to get anything agreeable: http://stupidpythonideas.blogspot.com/2013/07/syntactic-takewhile.html
<= kor until you reach the first one.os.path.commonprefix, but it made me wonder about ways of halting aforloop early.takewhilefromitertoolsfor that purpose.