Python - How to sort a list of lists by the fourth element in each list?

I would like to sort the following list of lists by the fourth element (integer) in each individual list.

unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']] 

How can i do this? Thank!

+51
python sorting list
Jul 09 '13 at 18:08
source share
2 answers
 unsorted_list.sort(key=lambda x: x[3]) 
+88
Jul 09 '13 at 18:09
source share

Use sorted() with key as follows:

 >>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']] >>> sorted(unsorted_list, key = lambda x: int(x[3])) [['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']] 

lambda returns the fourth element of each of the internal lists, and the sorted function uses this to sort the list. This assumes that int(elem) will not work for a list.

Or use itemgetter (as Ashwini commented, this method will not work if you have string representations of numbers, as they are tied to something for 2 + digits)

 >>> from operator import itemgetter >>> sorted(unsorted_list, key = itemgetter(3)) [['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']] 
+25
Jul 09 '13 at 18:09
source share



All Articles