Sort List By Second (or Nth) Element In Python: 1 Line Of Code

How do you sort a list of lists by the second element using Python?

To sort a list of lists by the second element in each list use the key parameter to either the .sort() list function (if modifying the original list) or the sorted() function (if returning a new list).

Here’s an example demonstrating how you can do this with code:

>>> list_2d = [['2nd', 2], ['3rd', 3], ['1st', 1]]
>>> list_2d.sort(key=lambda x: x[1])
>>> print(list_2d)
[['1st', 1], ['2nd', 2], ['3rd', 3]]

As you can see from the above code the key parameter in the .sort() list function uses a lambda expression which takes each list and extracts the second element. This is used as the key to determine how each list will be sorted.

This approach mutates the original list.

If you need to return a new list then use the sorted() built-in function, like so:

>>> list_2d = [['6th', 6], ['4th', 4], ['5th', 5]]
>>> sorted(list_2d, key=lambda x: x[1])
[['4th', 4], ['5th', 5], ['6th', 6]]
>>> print(list_2d)
[['6th', 6], ['4th', 4], ['5th', 5]]

The result from the sorted function produces a new 2d list, as can be seen when printing the original list_2d – this has not changed.

Sort List By Value

With this same technique, you should be able to sort a list if lists by any index within the lists. Whether it be the second or third or… nth index within the list, the same process occurs: use the key parameter referencing a lambda function that extracts the element you want to compare across all lists .


To sort a list of lists by the second element use the key property in either the .sort() list method or the sorted() function which is set to lambda x: x[1] where 1 in the lambda function represents the nth index you would want to sort the lists by.

Ryan Sheehy

Author of, Ryan has been dabbling in code since the late '90s when he cut his teeth by exploring VBA in Excel when trying to do something more. Having his eyes opened with the potential of automating repetitive tasks, he expanded to Python and then moved over to scripting languages such as HTML, CSS, Javascript and PHP. When he is not behind a screen, Ryan enjoys a good bush walk with the family during the cooler months, and going with them to the beach during the warmer months.

Recent Posts