Python: Sorting List of Tuples More Effectively

Python: Sorting List of Tuples More Effectively

A list of tuples is a list contains a collection of tuples, for example:

[(4, 8, 6), (7, 3, 9), (1, 1, 3)]

This tutorial will show you effective methods to sort a list of tuples.

Sort List of Tuples using the sort() function

sort() is a built-in function that sorts a list ascending by default. We can use this method to sort a list of tuples.

Note: by default, this method sort by the first element of tuples.

Sort by default Example

Syntax:

list.sort() 

Example:

# List of tuple
li = [(4, 8, 6), (7, 3, 9), (1, 1, 3)]

# Sort List
li.sort()

# Print List
print(li)

Output:

[(1, 1, 3), (4, 8, 6), (7, 3, 9)]

As you can see, our list has been sorted by the first element of tuples.

reverse the output:

#List
li = [(4, 8, 6), (7, 3, 9), (1, 1, 3)]

# Sort and Reverse List
li.sort(reverse=True)

# Print List
print(li)

Output:

[(7, 3, 9), (4, 8, 6), (1, 1, 3)]

In the following example, we'll see how to sort by the second element of tuples.

Sort by a specific element of tuples Example

In the following example, we'll sort by the second element using the bellow syntax:

li.sort(key=lambda x:x[1])

Example:

# List of tuple
li = [(4,1,8), (7,3,9), (1,2,6)]

# Sort List by the second element
li.sort(key=lambda x: x[1])

# Print List
print(li)

Output:

[(4, 1, 8), (1, 2, 6), (7, 3, 9)]

key: A function of sorting criteria.

x[1]: Element's index we want to be sorted by it.

If you got the IndexError: tuple index out of range issue, please check out How to solve IndexError list index out of range.

 

If the Lamba looks difficult for you, you can use itemgetter() instead:

Syntax:

itemgetter(index)

Example:

from operator import itemgetter

# List of tuple
li = [(4,1,8), (7,3,9), (1,2,6)]

# Sort List by the second element
li.sort(key=itemgetter(1))

# Print List
print(li)

Output:

[(4, 1, 8), (1, 2, 6), (7, 3, 9)]

Sort List of Tuples using the sorted() function

sorted() sorted list of a given iterable and return the result as a list. In addition, this function sort ascending(by default) or descending.

Syntax:

sorted(iterable, key=key, reverse=reverse) 

Example

Now, let us sort a list of tuples by default.

# List of tuple
li = [(4, 8, 10), (7, 3, 5), (1, 2, 1)]

# Sort List using sotred()
s = sorted(li)

# Print List
print(s)

Output:

[(1, 2, 1), (4, 8, 10), (7, 3, 5)]

By default, sorted() sort by the first element. Moreover, you can sort by any item you want using Lamba or itemgetter functions as we did with the previous method.

Conclusion

Here, we have learned how to sort a list of tuples using sort() and sorted() methods. We have also known how to sort by tuple's element.

See you later!