title: Does Python optimize lambda x: x
body: <p><a href="https://stackoverflow.com/questions/22203740/get-minimum-and-maximum-values-from-a-for-in-loop/22204272#22204272">So I wrote some code for a max/min that assumes a bottleneck on generating the data</a> (else I'd just use <code>max</code> and <code>min</code>), and it takes a key function, which if not given uses an identity function:</p>
  
  <pre><code>if key is None:
      key = lambda x: x
  </code></pre>
  
  <p>and then later:</p>
  
  <pre><code>for i in iterable:
      key_i = key(i)
  </code></pre>
  
  <p>And since the bottleneck is on the generator, the question might be moot, but if there's no key, I call <code>lambda x: x</code> for every item. <em>I would assume that Python could optimize this identity function away. Can someone tell me if it does?</em> Or if it doesn't, how expensive is it? Is there a way to do this better without doubling my line count (e.g. ternary operators)? </p>