Sort a list where there are strings, floats and integers
<p>I need some help because I wanted to know if there is a way in Python to sort a list where there are strings, floats and integers in it.</p>

<p>I tried to use list.sort() method but of course it did not work.</p>

<p>Here is an example of a list I would like to sort :</p>

<pre><code>    l = [1, 2.0, "titi", True, [2, 3, 4, [3, [3, 4]], 5]]
</code></pre>

<p>I would like it to be sorted by value by floats and ints, and then by type : floats and ints first, then strings, then booleans and then lists. I would like to use Python 2.7 but I am not allowed to..</p>

<p>Python's comparison operators wisely refuse to work for variables of incompatible types. Decide on the criterion for sorting your list, encapsulate it in a function and pass it as the <code>key</code> option to <code>sort()</code>. For example, to sort by the <code>repr</code> of each element (a string):</p>

<pre><code>l.sort(key=repr)
</code></pre>

<p>To sort by type first, then by the contents:</p>

<pre><code>l.sort(key=lambda x: (str(type(x)), x))
</code></pre>

<p>The latter has the advantage that numbers get sorted numerically, strings alphabetically, etc. It will still fail if there are two sublists that cannot be compared, but then you must decide what to do-- just extend your key function however you see fit.</p>

python sorting python-3.3