Error: object of type 'int' has no len()
<p>I have a function that is supposed to take an array and sort it from the smallest string size to the largest and then print it by using injection sort.</p>

<p>On the line: <code>while (j &gt;=0) and (len(b[j]) &gt; key):</code></p>

<p>I get this error: </p>

<blockquote>
  <p>object of type 'int' has no len()</p>
</blockquote>

<p>Code:</p>

<pre><code>def list_sort(b):
    for i in range(1, len(b)):
        key = len(b[i])
        j = i - 1 
        while (j &gt;=0) and (len(b[j]) &gt; key):
            b[j+1] = b[j]
            j = j - 1
        b[j+1] = key
    for i in range( len(b) ):
        print (b[i])

list_sort(name)
</code></pre>

<p>It sounds like you have a mixed list of integers and strings and want to sort by length of the strings. If that is the case, convert the entire list to like types -- strings -- before sorting. </p>

<p>Given:</p>

<pre><code>&gt;&gt;&gt; li=[1,999,'a','bbbb',0,-3]
</code></pre>

<p>You can do:</p>

<pre><code>&gt;&gt;&gt; sorted(map(str, li), key=len)   
['1', 'a', '0', '-3', '999', 'bbbb']
</code></pre>

<p>If you want a two key sort by length then ascibetible, you can do:</p>

<pre><code>&gt;&gt;&gt; sorted(map(str, li), key=lambda e: (len(e), e))
['0', '1', 'a', '-3', '999', 'bbbb']
</code></pre>

<p>You can sort without changing the object type by adding <code>str</code> to the key function:</p>

<pre><code>&gt;&gt;&gt; sorted(li, key=lambda e: (len(str(e)), str(e)))
[0, 1, 'a', -3, 999, 'bbbb']
</code></pre>

python arrays sorting