Quick sort in Python
Recursive step of quick sort: sorts the smaller and larger lists by calling itself, then joins them around the equal items. Base case len(items) <= 1 stops it.
Understanding Quick sort in Python in VCE Software Development U3O1
What it does: This list comprehension collects every item that is less than the pivot into the smaller list. A list with 0 or 1 items is already sorted, so it is returned as is. Using >= 1 would return almost every list unsorted, and the recursion would never happen properly. Smaller values must come first for an ascending sort, then the equal items, then the larger values. Sorted input is a useful edge case. The function should return the same order, and it checks that the smaller and larger lists are built correctly. This base case stops quick_sort calling itself forever, because a list of 0 or 1 items needs no sorting.
Common mistakes: The base case must stop on lists of length 0 or 1, so it should be len(items) <= 1. With >= 1, every non-empty list is returned unsorted, and an empty list would crash at items[0]. Items smaller than the pivot belong in the smaller list, so this should be smaller.append(x). Putting them in larger leaves the smaller list empty and the sort is wrong.
Free printable worksheet with full answer key — or add this module to a class and your students practise it interactively.
This module's key terms are also in a printable crossword (Modules 142–155) and word search (Modules 142–166).
Take this worksheet further — free with Cloodit
Each concept is reinforced from every angle — learned, then applied, then tested.
Cloodit turns curriculum-aligned coding content into journeys students work through one biome at a time.
Over 100 of them, across seven natural biomes.
Turns their work into revision material ready for Flash Cards and Exam study.
Live, competitive practice for the start of the lesson or a teacher-led lesson finisher.
Honour your top performers, or encourage a student who's trying hard — ready to print in seconds.
Quick Questions
Match the Pairs
Key Term
return quick_sort(smaller) + equal + quick_sort(larger)Fill in the Blanks
Spot the Error
Student with a class code? Join your class →