Python Practice › Loop Programs › Program 86
Sort a list with loops
Write a Python program to sort a list using loops (without sort()).
Input
[6, 8, 2, 3, 1, 0, 5]
Output
[0, 1, 2, 3, 5, 6, 8]
Approach
- Bubble sort: compare neighbours and swap them when they are in the wrong order; repeat.
Solution
numbers = [6, 8, 2, 3, 1, 0, 5]n = len(numbers)for i in range(n - 1): for j in range(n - 1 - i): if numbers[j] > numbers[j + 1]: numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]print(numbers)Output
[0, 1, 2, 3, 5, 6, 8]
Line by line
Line 3
After each outer pass the largest remaining item has “bubbled” to the end.
Line 4
The inner loop can stop earlier each time, because the end is already sorted.
Line 6
Tuple assignment swaps the two neighbours.
Learn the concept
New to this topic? Read the lesson, then come back.