5 Best Ways to Sort by Rear Character in Python String Lists

πŸ’‘ Problem Formulation: Suppose we have a list of strings and we want to sort it based on the last character of each string, disregarding the other characters. For example, given the input ['banana', 'apple', 'orange'], our desired output would be ['banana', 'orange', 'apple'] because the last characters sorted alphabetically are ‘a’, ‘e’, and ‘n’.

Method 1: Using a Custom Sort Key Function

Python’s built-in sorted() function can accept a custom key function, which can return the last character of a string. This method provides a clear and concise way to sort a list by the rear character of each element.

Here’s an example:

strings = ['banana', 'apple', 'orange']
sorted_list = sorted(strings, key=lambda x: x[-1])
print(sorted_list)

Output:

['banana', 'orange', 'apple']

This code uses a lambda function as the key, which takes each string, x, and returns its last character, x[-1]. The sorted() function then sorts the list based on these returned values.

Method 2: Using the operator Module

The operator module’s itemgetter() function can be used to facilitate the sorting process by providing a way to retrieve the last character effectively.

Here’s an example:

from operator import itemgetter
strings = ['banana', 'apple', 'orange']
sorted_list = sorted(strings, key=itemgetter(-1))
print(sorted_list)

Output:

['banana', 'orange', 'apple']

Instead of a lambda, this snippet uses itemgetter(-1) which creates a function that extracts the last character from each string for sorting purposes.

Method 3: Using a For Loop and Custom Sorting

Sometimes we need a more hands-on approach. A for loop can be used to append the last character of each string to a new list, sort that list, and then align the original list according to the sorted last characters.

Here’s an example:

strings = ['banana', 'apple', 'orange']
sort_helper = [(s[-1], s) for s in strings]
sorted_helper = sorted(sort_helper)
sorted_list = [s for _, s in sorted_helper]
print(sorted_list)

Output:

['banana', 'orange', 'apple']

The code creates a list of tuples, each containing the last character and the whole string. After sorting by the first element of the tuple, the code reconstructs the list of strings, now in sorted order by the last character.

Method 4: Custom Class with __lt__ Method

By defining a custom class that overrides the less-than method, __lt__, we can control how objects are compared during sorting. This is a more intricate approach but allows for high customizability.

Here’s an example:

class CustomString(str):
    def __lt__(self, other):
        return self[-1] < other[-1]

strings = ['banana', 'apple', 'orange']
sorted_list = sorted(map(CustomString, strings))
print(sorted_list)

Output:

['banana', 'orange', 'apple']

This code snippet defines a CustomString class that extends Python’s str type and overrides the __lt__ method to compare strings by their last character. The strings list is then mapped to the custom class and sorted.

Bonus One-Liner Method 5: In-Place Sorting with sort()

The list‘s sort() method can be utilized to sort the list in place, modifying the original list instead of creating a sorted copy.

Here’s an example:

strings = ['banana', 'apple', 'orange']
strings.sort(key=lambda x: x[-1])
print(strings)

Output:

['banana', 'orange', 'apple']

Similar to Method 1, this one-liner uses a lambda function as the sort key but uses the list.sort() method to modify the list in place, rather than creating a new list.

Summary/Discussion

  • Method 1: Custom Sort Key Function. Straightforward. May be slower for complex key functions.
  • Method 2: operator Module. Concise and potentially faster than a lambda key function. Requires importing an additional module.
  • Method 3: Using a For Loop and Custom Sorting. Offers more control over the sorting process. More verbose and potentially less efficient.
  • Method 4: Custom Class with __lt__. Highly customizable. More complex and overkill for simple tasks.
  • Bonus Method 5: In-Place Sorting with sort(). Efficient as it does not create a copy. Modifies the original list, which may not always be desirable.