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
- Swapping without the tuple trick â
a = b; b = adestroys the first value; usea, b = b, aor a temp variable. - Writing
result = nums.sort()â.sort()returnsNone, so result becomes None (a famous AttributeError two lines later). - Off-by-one in the inner loop:
range(len(nums))makesnums[j + 1]walk past the end and raise IndexError. - Forgetting the shrinking
- iâ the sort still works but re-compares already-final slots. - Assuming mixed types sort â
sorted([3, "1"])raises TypeError; convert to one type first.
Practice on PyDebug
Turn the idea into a debugging habit with these free browser exercises: