title: Frustrated with Python's sorted Built-in (with range and lambda as key)
body: <p>I encountered something that makes no sense to me. See this use of <code>sorted</code> with <code>range</code> and <code>lambda</code>:</p>
  
  <pre><code>sorted(range(-5, 6), key=lambda x: x * x)
  </code></pre>
  
  <p>Which outputs this in the Python shell:</p>
  
  <pre><code>[0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5]
  </code></pre>
  
  <p>Now, for the life of me, I don't get this! I've been playing around with <code>sorted</code>, <code>lambda</code>, and <code>range</code>, and it doesn't make sense. For example, if you run the <code>range</code> bit in a for loop, you get something like this:</p>
  
  <pre><code>&gt;&gt;&gt; for i in range(-5, 6):
  ...     print(i)
  -5
  -4
  ...
  0
  ...
  4
  5
  </code></pre>
  
  <p>And the <code>lambda</code> bit:</p>
  
  <pre><code>&gt;&gt;&gt; (lambda x: x * x)(-5)
  25
  </code></pre>
  
  <p>But putting it all together... I don't understand how using the <code>key</code> this way makes the order independent of the sign.</p>
  
  <p>But this makes sense to me:</p>
  
  <pre><code>&gt;&gt;&gt; sorted(range(-5, 6), key=lambda x: abs(x))
  [0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5]
  </code></pre>
  
  <p>Can someone shed some light on this?</p>