To sort the list of lists in the second column, use operator.itemgetter() for convenience and clarity:
from operator import itemgetter outputlist = sorted(inputlist, key=itemgetter(1), reverse=True)
or to sort by location:
from operator import itemgetter inputlist.sort(key=itemgetter(1), reverse=True)
itemgetter() slightly faster than using lambda for a task.
Demo:
>>> from operator import itemgetter >>> inputlist = [ ... [1, 0.23], ... [2, 0.39], ... [4, 0.31], ... [5, 0.27], ... ] >>> sorted(inputlist, key=itemgetter(1), reverse=True) [[2, 0.39], [4, 0.31], [5, 0.27], [1, 0.23]]
You will only see your exception if you had floating point values ββin your input list directly:
>>> inputlist.append(4.2) >>> inputlist [[1, 0.23], [2, 0.39], [4, 0.31], [5, 0.27], 4.2] >>> sorted(inputlist, key=itemgetter(1), reverse=True) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'float' object is not subscriptable
(For Python 3, the Python 2 error message is slightly different, as a result, instead of TypeError: 'float' object has no attribute '__getitem__' ).
This is because the itergetter(1) call is applied to all elements of the external list, but only works with nested ordered sequences, and not with one added floating point value.