Selection sort in Python
A sorting algorithm that uses nested loops to find the smallest remaining item, then swaps it into place with a, b = b, a. It repeats for each position until the list is sorted.
Understanding Selection sort in Python in VCE Software Development U3O1
What it does: Starting at i + 1 means the inner loop only checks items that are not sorted yet, looking for the minimum. Comparing nums[j] with the current smallest nums[m] and updating m tracks where the minimum is. The outer loop picks each position (0, 1, 2 ...) that needs the correct item placed into it. Python can swap in a single line with a, b = b, a. Using two separate assignments would overwrite one value and lose it. The smallest item (1) is found and swapped with the item in position 0 (5), giving [1, 2, 9, 5]. The a, b = b, a pattern swaps two items in one line, which puts the minimum into its correct place.
Common mistakes: The inner loop must only check the unsorted items after position i, so it should start at i + 1. Starting at i - 1 looks back at the sorted part (and at -1 when i is 0). m holds the index of the smallest item found so far in the unsorted part. It must start at i, the current position, not at 0, which is the start of the whole list.
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
selection sortFill in the Blanks
Spot the Error
Student with a class code? Join your class →