python sorting error: TypeError: 'list' object is not callable
<p>I am trying to sort a list of list based on the first item of each element:</p>

<pre><code>def getKey(item):
    return item[0]    

def myFun(x):
    return sorted(x, key= getKey(x))

my_x = [[1,100], [5,200], [3,30]]

myFun(my_x)
</code></pre>

<p>I want the sorting based on the first item of each element, i.e. 1, 5 and 3. The expected result should be: <code>[[1,100], [3,30], [5,200]]</code></p>

<p>However, I got the error below:</p>

<pre><code>TypeErrorTraceback (most recent call last)
&lt;ipython-input-7-4c88bbc1a944&gt; in &lt;module&gt;()
      3 
      4 my_x = [[1,100], [5,200], [3,30]]
----&gt; 5 myFun(my_x)

&lt;ipython-input-7-4c88bbc1a944&gt; in myFun(x)
      1 def myFun(x):
----&gt; 2     return sorted(x, key= getKey(x))
      3 
      4 my_x = [[1,100], [5,200], [3,30]]
      5 myFun(my_x)

TypeError: 'list' object is not callable
</code></pre>

<p>Any idea what I did wrong here? Thanks!</p>

<p>You don't need to call the function <code>getKey</code>. The signature of <a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow"><code>sorted</code></a> requires you pass the <code>key</code> argument as a callable:</p>

<pre><code>sorted(x, key=getKey)
</code></pre>

python list python-2.7 sorting