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><strong>UPDATE</strong></p>

<p><code>sorted</code>'s <code>key</code> attribute should be callable, so instead of assigning <code>key=getKey()</code> you need to <code>key=getKey</code></p>

<p><strong>INITIAL ANSWER</strong>(could be useful if you want to make code look better):</p>

<p><del>There is no such method as <code>getKey</code>, but</del> there is <a href="https://docs.python.org/2/library/operator.html#operator.itemgetter" rel="nofollow"><code>itemgetter</code></a> from <a href="https://docs.python.org/2/library/operator.html#operator" rel="nofollow"><code>operator</code></a> package</p>

<pre><code>from operator import itemgetter


def myFun(x):
    return sorted(x, key=itemgetter(0))

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

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

<p><strong>To the downvoters</strong>:</p>

<p>It's clearly said that</p>

<blockquote>
  <p>I want the sorting based on the first item of each element</p>
</blockquote>

<p>And if you think that you would sort presented list only with <code>sorted()</code>, you are wrong.</p>

<pre><code>&gt;&gt;&gt; my_x = [[1,100], [5,200], [3,30], [1,30]]
&gt;&gt;&gt; myFun(my_x)
[[1, 100], [1, 30], [3, 30], [5, 200]]
&gt;&gt;&gt; sorted(my_x)
[[1, 30], [1, 100], [3, 30], [5, 200]]
</code></pre>

<p>So <code>sorted</code> is not based only on first argument, as OP wanted</p>

<p><strong>INITIAL ANSWER'S UPDATE</strong> </p>

<p>Also, when i answered there was no <code>getKey</code> method, you can look at <a href="http://stackoverflow.com/posts/39730477/revisions">OP post edit history</a></p>

<p>And so OP post now have <code>getKey</code> method you can look at the appropriate @MosesKoledoye 's <a href="http://stackoverflow.com/a/39730625/3124746">answer</a></p>

python list python-2.7 sorting