× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Is it good to store as a variable for "if condition" in iteration

Utkarsh Upadhyay
Apr 27, 2015
<p>Easy enough to check (IPython console):</p> <pre><code>In [9]: def foo(x): print "Called." return True In [10]: [1 for x in xrange(10) if foo(x)] Called. Called. Called. Called. Called. Called. Called. Called. Called. Called. Out[10]: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] </code></pre> <p>As to function calls getting optimized, that is usually the turf of a Just In Time compiler. So in case of PyPy, after a set number of iterations, the compiler may decide that this is a hotspot and may try to optimize the internals of the function, but I don't think that such optimizations are powerful enough to reduce the complexity from <code>O(n)</code> to <code>O(1)</code>.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/29678589/Is%20it%20good%20to%20store%20as%20a%20variable%20for%20%22if%20condition%22%20in%20iteration/29678686">Stack Overflow</a>.</p>
comments powered by Disqus