# 5 Best Ways to Sort a List of Lists by Nth Element in Python

π‘ Problem Formulation:

Sorting a list of lists by an element at a specific position (the nth element) is a common task in programming. Suppose you have a list of lists where each sublist contains multiple elements. For example, you have `[["pear", 3], ["apple", 2], ["banana", 1]]` and want to sort it based on the second element of each sublist, resulting in `[["banana", 1], ["apple", 2], ["pear", 3]]`. This article covers various methods to achieve this in Python.

## Method 1: Using the Sorted Function and Lambda

The `sorted()` function in combination with a lambda function provides a clean, readable way to sort a list of lists by any nth element. The `sorted()` function returns a new sorted list, and the lambda function within it specifies the key to sort by β the nth element in this case.

Here’s an example:

```data = [["pear", 3], ["apple", 2], ["banana", 1]]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)```

Output:

`[["banana", 1], ["apple", 2], ["pear", 3]]`

This code snippet sorts the list `data` based on the second element of each sublist, as indicated by the lambda function `lambda x: x[1]`. Sorted returns a new list that is sorted in ascending order.

## Method 2: Using the sort() Method and a Custom Function

If you prefer to sort the list in place, you can use the list method `sort()` with a custom function defining the sorting. The second parameter to `sort()`, `key=`, allows you to pass a custom function that returns the value by which to order the sublists.

Here’s an example:

```def get_nth_element(sublist, n):
return sublist[n]

data = [["pear", 3], ["apple", 2], ["banana", 1]]
data.sort(key=lambda x: get_nth_element(x, 1))
print(data)```

Output:

`[["banana", 1], ["apple", 2], ["pear", 3]]`

Here, the `sort()` method organizes the original `data` list by using a lambda function to call a custom function `get_nth_element`, which fetches the nth element of a sublist for sorting.

## Method 3: Using operator.itemgetter

Python’s operator module provides `itemgetter()` to facilitate sorting lists by a specific item. When used as a key in sorting functions, `itemgetter()` can quickly extract the required sortable element from each sublist.

Here’s an example:

```from operator import itemgetter

data = [["pear", 3], ["apple", 2], ["banana", 1]]
sorted_data = sorted(data, key=itemgetter(1))
print(sorted_data)```

Output:

`[["banana", 1], ["apple", 2], ["pear", 3]]`

The function `itemgetter(1)` is a very efficient way to retrieve the second item from each sublist, which is then utilized by the `sorted()` function to sort the list `data`.

## Method 4: Using List Comprehension and zip

List comprehension with zip can sort a list of lists by first restructuring the list relative to the nth element. This unconventional technique can be used for complex sorting scenarios, but may not be straightforward for all users.

Here’s an example:

```data = [["pear", 3], ["apple", 2], ["banana", 1]]
sorted_data = [x for _, x in sorted(zip([sublist[1] for sublist in data], data))]
print(sorted_data)```

Output:

`[["banana", 1], ["apple", 2], ["pear", 3]]`

This code constructs a sorted list by first creating pairs of nth elements and sublists, sorting by the first element in each pair, and then extracting the sublist again through list comprehension.

## Bonus One-Liner Method 5: Using a List Slice

A quick one-liner method utilizes list slicing in a sorted function call. While concise, this method sacrifices some readability and is not very intuitive.

Here’s an example:

```data = [["pear", 3], ["apple", 2], ["banana", 1]]
sorted_data = sorted(data, key=lambda x: x[1:])
print(sorted_data)```

Output:

`[["banana", 1], ["apple", 2], ["pear", 3]]`

Although cryptic, this one-liner uses a lambda function to create a slice of each sublist starting from the nth element and passes it to `sorted()` as the sort key.

## Summary/Discussion

• Method 1: Sorted with Lambda. Strengths: Easy to read; returns a new sorted list. Weaknesses: Can be less efficient for large lists.
• Method 2: sort() with a Custom Function. Strengths: Sorts in place; allows for complex custom sorting logic. Weaknesses: Slightly more verbose; modifies the original list.
• Method 3: operator.itemgetter. Strengths: Very efficient; clean syntax. Weaknesses: Requires import; less transparent than a lambda function.
• Method 4: List Comprehension and zip. Strengths: Powerful for complex sorting. Weaknesses: Less readable; potentially confusing.
• Bonus Method 5: List Slice in a One-Liner. Strengths: Very concise. Weaknesses: Impairs readability; intangible in complex scenarios.