Start learning free

LESSON 21 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V1 in Python: Sorting Lines with sorted()

Practice Read the full explanation

Build a tiny version of the Unix sort command. Given a list of lines, return them sorted in ascending order by character code (like LC_ALL=C sort: uppercase letters come before lowercase ones, "Zebra" before "apple", and an empty line comes first), joined by newline characters (\n). Duplicates are all kept. If the list is empty, return the empty string.

Function signature:

def sortLines(self, lines: List[str]) -> str:

Example:

Input: lines = ["banana", "apple", "cherry"]

Output: "apple\nbanana\ncherry"

When printed:
apple
banana
cherry

Use Python's built-in sorted for ascending order, then join with "\n".

The full solution:
class Solution:
    def sortLines(self, lines):
        sortedLines = sorted(lines)
        return "\n".join(sortedLines)

STEP 1 OF 2
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Sort V1 in Python, explained

    Problem overview

    This is the first version of a small sort command. The method sortLines takes a list of lines and returns them in ascending order, joined by "\n". Duplicates are all kept, and an empty list gives the empty string.

    For ["banana", "apple", "cherry"] the result is "apple\nbanana\ncherry". Printed, each word is on its own line.

    The order is by character code, as in LC_ALL=C sort. That means every uppercase letter comes before every lowercase letter, so "Zebra" comes before "apple", and an empty line, being the shortest string, comes first.

    Approach

    Python already compares strings by the code of each character, from left to right, so the built-in sorted does exactly what the task asks. There is nothing to write by hand except gluing the result into one string.

    Two details matter:

    • sorted(lines) returns a new list and leaves lines untouched. The list method lines.sort() sorts in place and returns None, so return "\n".join(lines.sort()) would raise an error.
    • "\n".join(items) puts the separator between items only, so there is no newline after the last line.

    How strings compare

    Python compares two strings character by character using each character's code point, the number ord returns. An uppercase "Z" has code 90 and a lowercase "a" has code 97, so "Zebra" < "apple" is True. When one string is a prefix of the other, the shorter one comes first, so "app" < "apple" is True and the empty string is smaller than every other string. Characters outside ASCII follow the same rule: sorted(["é", "z", "a"]) gives ['a', 'z', 'é'], because the code of "é" is larger than that of "z".

    The same function sorts any iterable of comparable items, and always returns a list: sorted("hello") is ['e', 'h', 'l', 'l', 'o']. Keep that in mind in this lesson only to remember that the input is a list of whole lines, not characters.

    Step by step

    1. Create sortedLines from sorted(lines).
    2. Return the sorted lines joined with a newline between each two.

    The solution in Python

    class Solution:
        def sortLines(self, lines):
            sortedLines = sorted(lines)
            return "\n".join(sortedLines)
    

    The difference between sorted and sort is easy to see with a small list:

    l = ["banana", "apple"]
    print(sorted(l), l)
    r = l.sort()
    print(r, l)
    
    ['apple', 'banana'] ['banana', 'apple']
    None ['apple', 'banana']
    

    The first line shows that sorted left l alone. The second shows that l.sort() returned None and changed l itself. Here the lesson's input list stays as the caller gave it, which is the safer behaviour.

    Complexity

    Sorting n lines takes O(n log n) comparisons (Python's sort is Timsort), and the new list takes O(n) extra space. The join is linear in the total length of the text.

    Edge cases and common mistakes

    These are the results of the solution on a few inputs:

    linesresult
    ["banana", "apple", "cherry"]"apple\nbanana\ncherry"
    ["apple", "Zebra", "", "banana", "apple"]"\nZebra\napple\napple\nbanana"
    ["b"]"b"
    []""
    • In the second row the empty line comes first, which is why the result starts with \n, and "Zebra" precedes both "apple"s.
    • Numbers written as text sort as text: sorted(["10", "9", "1"]) gives ['1', '10', '9']. A later version of this tool deals with that.
    • Sorting without caring about case, for example with key=str.lower, would put "apple" before "Zebra". That is not what this version asks for.
    • Don't add a trailing newline. The join already puts exactly one separator between each pair of lines.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free