Python Snippet

Quick Sort One-Liner in Python

Difficulty: Medium

The functional Quicksort one-liner in Python is a classic teaching artifact: it is short enough to fit on one line and shows comprehensions plus recursion working together. This snippet covers the three-way functional one-liner, an in-place Lomuto-partition variant for performance, and a benchmark contrast against `sorted` to show why the one-liner is for teaching, not production.

Code Snippets
/

Quick Sort One-Liner in Python

Quick Sort One-Liner in Python

The functional Quicksort one-liner in Python is a classic teaching artifact: it is short enough to fit on one line and shows comprehensions plus recursion working together. This snippet covers the three-way functional one-liner, an in-place Lomuto-partition variant for performance, and a benchmark contrast against `sorted` to show why the one-liner is for teaching, not production.

Python
Medium
3 snippets
algorithms
sorting
recursion
py-list-comprehensions

659 views

7

The functional Quicksort partitions the list into 'less than or equal to pivot' and 'greater than pivot' using two list comprehensions, then recursively sorts each side and concatenates. The base case (len(xs) <= 1) covers both the empty list and the single-element list. This is the teaching version: it is concise enough to fit on a slide and demonstrates Quicksort's divide-and-conquer shape clearly. The trade-off is O(n) extra space per recursive call (the two new lists), which makes it asymptotically slower than the in-place version for large inputs.