5 Best Ways to Sort a List of Strings in Python by Length and Alphabetically

πŸ’‘ Problem Formulation: When working with lists of strings, a common task is to arrange the items in a structured order. The goal here is to sort a given list of strings first by their length and then alphabetically. For instance, given the input ["banana", "apple", "cherry", "kiwi"], the desired output would be ["kiwi", "apple", "banana", "cherry"], where the strings are sorted by their increasing length, and strings of the same length are further sorted alphabetically.

Method 1: Using a Custom Sort Function

Python’s sort() method can be customized with a key function that guides the sorting process. By combining the length of strings with their alphabetical order, you can perform a multi-criteria sort.

β™₯️ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month

Here’s an example:

strings = ["banana", "apple", "cherry", "kiwi"]
strings.sort(key=lambda x: (len(x), x))
print(strings)

Output:

['kiwi', 'apple', 'banana', 'cherry']

This snippet defines a lambda function as the key which returns a tuple where the first element is the length of the string, and the second is the string itself. Python sorts tuples lexicographically, so strings are first sorted by length and then alphabetically.

Method 2: Using the operator module

The operator module provides the itemgetter function which can be used to construct a key function that is more efficient than a lambda.

Here’s an example:

from operator import itemgetter
strings = ["apple", "kiwi", "banana", "cherry"]
strings.sort(key=itemgetter(len, str))
print(strings)

Output:

['kiwi', 'apple', 'banana', 'cherry']

This code uses the itemgetter to generate a key function that behaves similarly to the lambda in Method 1. However, by using itemgetter, we avoid the overhead associated with lambda expressions, which can be beneficial for larger datasets.

Method 3: Sorting with a Custom Class

Defining a custom class with a __lt__ (less than) method allows for full control over the sorting order. This can help make complex sorting conditions more readable.

Here’s an example:

class SortableString:
    def __init__(self, string):
        self.string = string

    def __lt__(self, other):
        return (len(self.string), self.string) < (len(other.string), other.string)

strings = ["apple", "banana", "cherry", "kiwi"]
sorted_strings = sorted([SortableString(s) for s in strings], key=str)
print([s.string for s in sorted_strings])

Output:

['kiwi', 'apple', 'banana', 'cherry']

This code wraps each string in a custom SortableString class that defines sorting logic inside the __lt__ method. The list is sorted and then unpacked to retrieve the original strings. This method enhances readability and encapsulates the sorting logic but may be overkill for simple tasks.

Method 4: Multiple Sorting Passes

You can achieve the desired sort by applying two sorting passes. First, sort the list alphabetically, and then sort it again by string length.

Here’s an example:

strings = ["cherry", "banana", "kiwi", "apple"]
strings.sort()
strings.sort(key=len)
print(strings)

Output:

['kiwi', 'apple', 'banana', 'cherry']

This code performs an initial alphabetical sort, which ensures that strings of the same length are already in alphabetical order before the final length sort. This two-pass approach is simple to understand but can be less efficient than a one-pass sort.

Bonus One-Liner Method 5: Using Sorted with A Custom Key

A one-liner approach combines the power of the sorted() function with a lambda to create the same sorting effect elegantly.

Here’s an example:

strings = ["banana", "kiwi", "apple", "cherry"]
sorted_strings = sorted(strings, key=lambda x: (len(x), x))
print(sorted_strings)

Output:

['kiwi', 'apple', 'banana', 'cherry']

Utilizing sorted() allows the same operation with a concise one-liner, and the output is a new sorted list, leaving the original list unmodified. This approach is elegant and maintains the functionality of the sort without changing the original list.

Summary/Discussion

  • Method 1: Custom Sort Function. Versatile and understandable. May be less efficient for large datasets.
  • Method 2: Operator Module. Efficient and clean. Requires an understanding of the operator module.
  • Method 3: Custom Class. Enhances readability for complex sorts. Overly complex for simple tasks.
  • Method 4: Multiple Sorting Passes. Easy to understand. Less efficient due to multiple passes.
  • Bonus Method 5: One-Liner with Sorted. Elegant and concise. Excellent for creating a sorted copy of the list.