Python sort list of tuples | descending, first, second, last, multiple elements, value, alphabetically

Python sort list of tuples using sort method needed key which sorts lists in place. And also offers a convenient way to sort tuples based on the index of tuple elements.

You can sort list of tuples by first and second element by using index or values.

  • tup[0] to sort on first tuple element
  • tup[1] to sort on second and so on.

1. Example sort by the First element value


[(‘P’, 1), (‘A’, 2), (‘M’, 3), (‘B’, 4)]

2. Example sort by the Second element value


[(‘A’, 2), (‘B’, 4), (‘M’, 3), (‘P’, 1)]

How to sort a list of tuples by the first element alphabetically in python?

You have a list of tuples like this:

And wanted to sort this list and get something like:

Answer: You can do it using a sort() or sorted() functions.

sorted() funciton

or sort() function

Python sort list of tuples descending

Here is an example of the sorting the list of tuples first by the descending order and alphabetically in python 3.

lst is a list of tuple with each tuple holding the value in the format (value, key) . And you want to sort it based on the key which is at index 0 of the tuple. In that case you should be calling the .sort() with key as:

Output: [(‘A’, 5), (‘B’, 6), (‘C’, 1), (‘D’, 4)]

Python sort list of tuples by multiple elements


Python sort list of tuples by multiple elements

How to sort list of tuples by last element in python?

Answer: Specify the key argument in the sorted function.

The sorted function (as well as the list.sort method) has an optional key argument which specifies what to sort the list on.

Output: [(2, 1), (3, 2), (1, 3)]

Do comment if you have any doubts on this tutorial.

IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.