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>

<blockquote>
  <p>If someone knows how to break from a list comprehension </p>
</blockquote>

<p>You can not break a list compression. </p>

<p>But you can modify your list comprehension with the <code>if</code> condition in <code>for</code> loop. With if, you can decide what values are needed to be the part of the list:</p>

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

<p>It is better to use simple <code>for</code> loop. In fact for loops are faster than list comprehension in terms of performance. Check <a href="http://stackoverflow.com/a/39518977/2063361">HERE</a> the comparison I did for another question.</p>

<p>Even though list comprehension should be preferred as they are clean and more readable. Again, it is opinion based: Readability V/S Speed. </p>

<p><strong>Suggestion</strong>:</p>

<p>Also, there is a easier way to achieve what you are doing via:</p>

<pre><code>import math
def find_zeros_in_factorial(n):
    num_str = str(math.factorial(n))
    return len(num_str)-len(num_str.rstrip('0'))
</code></pre>

<p>The idea here is to subtract the length of the string with the length of string <em>without zeroes</em> at the end.</p>

python list-comprehension break