Python Sort List of Strings by Length and Alphabetically

5/5 - (1 vote)

πŸ’‘ Problem Formulation: In various programming tasks, we may be required to sort a list of strings not only based on alphabetical order but also by the length of each string.

Suppose we have a list of strings like ["banana", "apple", "cherry", "blueberry"].

We want to organize this list so that it’s sorted by the length of each string and, for strings of the same length, sort them alphabetically.

The desired output for this list would be ["apple", "banana", "cherry", "blueberry"].

If you only want to sort by length, check out my article here:

πŸ‘‰ Python Sort List of Strings by Length

Method 1: Using a Custom Sorting Function

Python’s sort() method can take a custom sorting function through its ‘key’ parameter. This function can be a lambda function that returns a tuple where the first element is the length of the string, and the second is the string itself, establishing a sort priority.

Here’s an example:

fruits = ["banana", "apple", "cherry", "blueberry"]
fruits.sort(key=lambda item: (len(item), item))
print(fruits)

This code snippet sorts the list of fruits by length and then alphabetically. The lambda function returns a tuple where the first element is the length of the string, ensuring primary sorting by length, and the second element is the string, which sorts the same-length strings alphabetically.

Method 2: Using the sorted() Function with a Custom Key

The sorted() function in Python works similarly to the sort() method but returns a new sorted list. You can provide a key function that, again, returns a tuple, first of the length, then the string itself.

Here’s an example:

fruits = ["banana", "apple", "cherry", "blueberry"]
sorted_fruits = sorted(fruits, key=lambda item: (len(item), item))
print(sorted_fruits)

In this code snippet, the list of fruits is sorted by length and alphabetically without altering the original list, as the sorted() function creates a new sorted list. The custom key function operates the same way as in Method 1.

Method 3: Using an Inline Function Definition

Instead of a lambda, you can define an inline function using def, which can improve readability when the sorting criteria are complex or if you’re avoiding lambda functions for stylistic reasons.

Here’s an example:

fruits = ["banana", "apple", "cherry", "blueberry"]

def sort_key(item):
    return len(item), item

fruits.sort(key=sort_key)
print(fruits)

The code snippet above defines a sorting key function sort_key that returns a tuple based on the string’s length and then the string itself. The sort() method sorts the list in-place using this function.

Method 4: Using Operator.itemgetter for Mixed Sorting

For cases where you are sorting objects or tuples and not just strings, operator.itemgetter can be useful. It can be used in combination with sorted() or sort() to sort the strings by length and then alphabetically if you first convert strings to tuples containing their length.

Here’s an example:

from operator import itemgetter
fruits = ["banana", "apple", "cherry", "blueberry"]
tuples = [(len(fruit), fruit) for fruit in fruits]
sorted_tuples = sorted(tuples, key=itemgetter(0, 1))
sorted_fruits = [fruit for _, fruit in sorted_tuples]
print(sorted_fruits)

This snippet first converts the fruit strings into tuples of (length, string), sorts the list of tuples, and then extracts the sorted strings. itemgetter(0, 1) specifies the tuple indices by which to sort.

Bonus One-Liner Method 5: Combining sorted() and List Comprehension

If you fancy one-liners, you can combine sorted() with a list comprehension to achieve the same result, albeit less readable for some.

Here’s an example:

fruits = ["banana", "apple", "cherry", "blueberry"]
print([fruit for _, fruit in sorted((len(fruit), fruit) for fruit in fruits)])

This complex one-liner creates a generator that produces tuples (length, string), sorts them, and then extracts the second element of each tuple to form the sorted list of strings.


Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!