break out of list comprehension?
<p>I am taking in an integer value, finding the factorial of that value and trying to count the number of trailing zeros if any are present. For example:</p>

<pre><code>def zeros(n):
    import math
    factorial = str(math.factorial(n))
    zeros_lst = [number if number == "0" (else) for number in factorial[::-1]]
    return len(zeros_lst)
</code></pre>

<p>The "else" in parenthesis is where the issue is occurring. I want to leave the loop if the as soon as it encounters a number that is not zero. I tried using break like you normally would, then looking up some examples but found nothing of similarity. </p>

<p>If someone knows how to break from a list comprehension or if is even possible that would be great. I am sure there are better ways to solve this problem, please post if you do. </p>

<p>There is no "breaking" in list comprehensions, but there are other tricks, e.g. <code>itertools.takewhile</code> which iterates an iterable while a condition is satisfied:</p>

<pre><code>&gt;&gt;&gt; from itertools import takewhile
&gt;&gt;&gt; 
&gt;&gt;&gt; values = [7, 9, 11, 4, 2, 78, 9]
&gt;&gt;&gt; list(takewhile(lambda x: x &gt; 5, values))
[7, 9, 11]
</code></pre>

<p>In your case (<em>I want to leave the loop if the as soon as it encounters a number that is not zero</em>):</p>

<pre><code>zeros_lst = list(takewhile(lambda x: x=="0", factorial[::-1]))
</code></pre>

python list-comprehension break