# 5 Best Ways to Sort a List of Tuples in Python by the Last Element

Rate this post

π‘ Problem Formulation: Suppose we have a list of tuples representing data, and we want to sort it so that the elements are arranged in increasing order based on the last value in each tuple. For example, given the list `[(1, 3), (3, 2), (2, 1)]`, we aim to sort it to `[(2, 1), (3, 2), (1, 3)]`, where each tuple is ordered by its second value.

## Method 1: Using the Sorted Function with a Custom Key

This method leverages Python’s built-in `sorted()` function, which is used for sorting iterables. We can pass a custom key function to it, which will return the last element of each tuple, thus allowing the sort to be performed based on the last elements.

Here’s an example:

```data = [(1, 7), (4, 4), (5, 5), (2, 3)]
sorted_data = sorted(data, key=lambda x: x[-1])
print(sorted_data)```

The output will be:

`[(2, 3), (4, 4), (5, 5), (1, 7)]`

We use a lambda function as the key that returns the last element of the tuple. The `sorted()` function then sorts the list of tuples based on these key values in ascending order.

## Method 2: Using the Sort Method with a Custom Key

Similar to Method 1, this technique utilizes the `list.sort()` method, which sorts the list in place. Again, a key function that fetches the last element of the tuple is provided.

Here’s an example:

```data = [(1, 5), (4, 2), (5, 3), (2, 4)]
data.sort(key=lambda x: x[-1])
print(data)```

The output will be:

`[(4, 2), (5, 3), (2, 4), (1, 5)]`

By employing a lambda function to return the last elements, we dictate the criteria for the `.sort()` method to arrange the tuples in the list in place without generating a new list.

## Method 3: Custom Function Using Itemgetter

For this approach, we import the `itemgetter` function from the `operator` module to replace the lambda function and achieve the same sorting behavior.

Here’s an example:

```from operator import itemgetter
data = [(3, 1), (1, 4), (2, 3), (4, 2)]
sorted_data = sorted(data, key=itemgetter(-1))
print(sorted_data)```

The output will be:

`[(3, 1), (4, 2), (2, 3), (1, 4)]`

Using `itemgetter(-1)` as the key for sorting, we can obtain a function specialized in fetching the last element of each tuple, making the sorting operation more efficient than using a lambda.

## Method 4: Sorting with a for Loop

This method manually implements sorting logic using a for loop. It’s a more fundamental approach and less Pythonic compared to previous methods.

Here’s an example:

```data = [(1, 3), (3, 2), (2, 1)]
sorted_data = []
while data:
min_tuple = min(data, key=lambda x: x[-1])
data.remove(min_tuple)
sorted_data.append(min_tuple)
print(sorted_data)```

The output will be:

`[(2, 1), (3, 2), (1, 3)]`

This code snippet finds the tuple with the minimum last element, removes it from the original list, and appends it to a new list iteratively until all elements are sorted.

## Bonus One-Liner Method 5: Using List Comprehensions

A concise, more advanced one-liner technique that sorts a list of tuples leveraging a list comprehension combined with the `sorted()` function.

Here’s an example:

```data = [(1, 3), (2, 1), (3, 2)]
sorted_data = sorted([(y, x) for x, y in data])
print(sorted_data)```

The output will be:

`[(1, 2), (2, 3), (3, 1)]`

This one-liner inverts each tuple before sorting, then sorts the list, effectively ordering by what was originally the last element, but needs inverting again for the desired format, which adds an extra step not shown in this example.

## Summary/Discussion

• Method 1: Using the Sorted Function with a Custom Key. This is a simple and commonly used approach. It’s highly readable, but creating a new list may not be memory efficient for large datasets.
• Method 2: Using the Sort Method with a Custom Key. It’s efficient as it sorts in place, saving memory; however, it modifies the original list, which may not be desired in all cases.
• Method 3: Custom Function Using Itemgetter. Similar to Method 1 but potentially faster due to the specialized function. However, it requires an import statement and is less readable for beginners.
• Method 4: Sorting with a for Loop. Offers granular control over sorting logic but is verbose and the least Pythonic way. It’s not recommended when simpler and more efficient methods are available.
• Bonus Method 5: Using List Comprehensions. Very compact, but less readable and requires the list to be manipulated back to its original tuple form after sorting.