Python sort() first element of list

DaveDave picture DaveDave · Jan 11, 2014 · Viewed 56.7k times · Source

I have a list that contains non specific amount of elements but every first element of the nested list is an identifier, I would like to use that identifier to sort the list in order

list = [['D', 'F', 'E', 'D', 'F', 'D'],['A', 'F', 'E', 'C', 'F', 'E'],['C', 'E', 'E', 'F', 'E', 'E'],['B', 'F', 'E', 'D', 'F', 'F']]

After its sorted

list = [['A', 'F', 'E', 'C', 'F', 'E'],['B', 'F', 'E', 'D', 'F', 'F'],['C', 'E', 'E', 'F', 'E', 'E'],['D', 'F', 'E', 'D', 'F', 'D']]

I am using python 3.3.3

Answer

Dan picture Dan · Jan 11, 2014

Python automatically sorts lists of lists by the first element. For example:

lol=[[1,2,3],[5,6,7],[0,9,9]]
sorted(lol)
[[0, 9, 9], [1, 2, 3], [5, 6, 7]]