← Back

Home â€ē Python programs

Sort a List in Python (With and Without sort())

⤇⤏āĨ‡ Hindi ā¤ŽāĨ‡ā¤‚ ā¤Ēā¤ĸā¤ŧāĨ‡ā¤‚

Problem statement

Arrange a list of numbers into ascending order — first by writing the sorting yourself (bubble sort), then the Pythonic way with the built-ins.

Approach 1: simple loop

Bubble sort: repeatedly walk the list, swapping any neighbouring pair that is out of order. Each full pass pushes the largest remaining value to the end, like a bubble rising.

nums = [5, 2, 9, 1]

for i in range(len(nums) - 1):
    for j in range(len(nums) - 1 - i):
        if nums[j] > nums[j + 1]:
            nums[j], nums[j + 1] = nums[j + 1], nums[j]

print(nums)
# Output: [1, 2, 5, 9]

The inner range shrinks by i because after pass 1 the last slot is already final, after pass 2 the last two are, and so on.

Approach 2: reusable function

Selection sort: find the smallest value in the unsorted part, swap it into place, repeat. Fewer swaps than bubble sort and just as easy to trace.

nums = [5, 2, 9, 1]

for i in range(len(nums) - 1):
    smallest = i
    for j in range(i + 1, len(nums)):
        if nums[j] < nums[smallest]:
            smallest = j
    nums[i], nums[smallest] = nums[smallest], nums[i]

print(nums)
# Output: [1, 2, 5, 9]

The outer loop fills position 0, then 1, then 2 — each with the smallest value not yet placed.

Approach 3: Pythonic alternative

Python's built-ins: sorted() returns a new sorted list, and .sort() sorts in place and returns None. Both accept a key and a reverse flag.

nums = [5, 2, 9, 1]

print(sorted(nums))            # [1, 2, 5, 9] — original untouched
print(sorted(nums, reverse=True))   # [9, 5, 2, 1]

words = ["banana", "fig", "apple"]
print(sorted(words, key=len))   # ['fig', 'apple', 'banana'] — by length

nums.sort()                    # in place; nums itself changes
print(nums)                    # [1, 2, 5, 9]

Exams ask for the hand-written loops; real code uses these — Timsort, the algorithm behind them, is heavily optimised and stable.

Dry run

Trace bubble sort on [5, 2, 9, 1], pass 1 only. Pair (5, 2): 5 > 2 → swap → [2, 5, 9, 1]. Pair (5, 9): in order, skip. Pair (9, 1): 9 > 1 → swap → [2, 5, 1, 9]. End of pass 1: 9 is locked in the last slot. Pass 2: (2, 5) skip; (5, 1) swap → [2, 1, 5, 9] — 5 locked. Pass 3: (2, 1) swap → [1, 2, 5, 9]. Done. Each pass fixes at least one slot, which is why the shrinking inner range is safe.

Common errors

Practice on PyDebug

Turn the idea into a debugging habit with these free browser exercises: