1. What is Sorting?
Sorting means arranging values in a fixed order. For numbers, this usually means smallest to largest. For words, this usually means alphabetical order.
marks = [55, 12, 90, 33, 71]
# After sorting:
# [12, 33, 55, 71, 90]
Ascending Order
Small to big.
[2, 5, 9, 12]
Descending Order
Big to small.
[12, 9, 5, 2]
Alphabetical Order
Words arranged from A to Z.
["apple", "banana", "mango"]
2. Two Main Ways to Sort Lists
| Method | Meaning | Changes Original List? | Returns |
|---|---|---|---|
list.sort() |
Sorts the same list directly. | Yes | None |
sorted(list) |
Creates a new sorted list. | No | New sorted list |
sort() when you are okay with changing the original list.
Use sorted() when you want to keep the original list safe.
3. Sorting with sort()
The sort() method sorts the original list itself.
This is called in-place sorting.
numbers = [40, 10, 30, 20]
numbers.sort()
print(numbers)
Output:
[10, 20, 30, 40]
Why does sort() return None?
Because sort() changes the original list directly.
It does not create a new list.
numbers = [4, 2, 9, 1]
answer = numbers.sort()
print(numbers)
print(answer)
Output:
[1, 2, 4, 9]
None
numbers = numbers.sort().
That will make numbers become None.
4. Sorting with sorted()
The sorted() function creates a new sorted list.
It does not damage the original list.
numbers = [40, 10, 30, 20]
new_numbers = sorted(numbers)
print("Original:", numbers)
print("Sorted:", new_numbers)
Output:
Original: [40, 10, 30, 20]
Sorted: [10, 20, 30, 40]
sorted() is safer when you want to preserve original data.
5. Sorting in Reverse Order
To sort from largest to smallest, use reverse=True.
marks = [55, 90, 12, 71, 33]
marks.sort(reverse=True)
print(marks)
Output:
[90, 71, 55, 33, 12]
Using sorted() with reverse
marks = [55, 90, 12, 71, 33]
top_marks = sorted(marks, reverse=True)
print("Original:", marks)
print("Sorted:", top_marks)
Output:
Original: [55, 90, 12, 71, 33]
Sorted: [90, 71, 55, 33, 12]
6. Sorting Strings
Python can sort strings alphabetically.
names = ["Ravi", "Amit", "Champak", "Zoya"]
names.sort()
print(names)
Output:
['Amit', 'Champak', 'Ravi', 'Zoya']
Capital and Small Letters Problem
Python sorts capital letters before small letters because it uses Unicode values.
words = ["banana", "Apple", "mango", "Cherry"]
print(sorted(words))
Output:
['Apple', 'Cherry', 'banana', 'mango']
To sort without worrying about capital and small letters, use key=str.lower.
words = ["banana", "Apple", "mango", "Cherry"]
print(sorted(words, key=str.lower))
Output:
['Apple', 'banana', 'Cherry', 'mango']
7. Sorting with key
The key parameter tells Python:
"Sort according to this rule."
Sort words by length
words = ["elephant", "cat", "tiger", "ant"]
words.sort(key=len)
print(words)
Output:
['cat', 'ant', 'tiger', 'elephant']
Here Python does not sort alphabetically.
It sorts by the result of len(word).
| Word | Length |
|---|---|
| elephant | 8 |
| cat | 3 |
| tiger | 5 |
| ant | 3 |
8. Sorting with lambda
A lambda function is a small one-line function.
It is very useful for custom sorting.
Sort tuples by second value
students = [
("Amit", 70),
("Ravi", 90),
("Zoya", 85),
("Meena", 60)
]
students.sort(key=lambda student: student[1])
print(students)
Output:
[('Meena', 60), ('Amit', 70), ('Zoya', 85), ('Ravi', 90)]
Here student[1] means marks.
So Python sorts students according to marks.
Sort by marks in descending order
students = [
("Amit", 70),
("Ravi", 90),
("Zoya", 85),
("Meena", 60)
]
students.sort(key=lambda student: student[1], reverse=True)
print(students)
Output:
[('Ravi', 90), ('Zoya', 85), ('Amit', 70), ('Meena', 60)]
9. Sorting by a Comparison Function
A comparison function compares two values at a time. It tells Python whether the first value should come before the second value, after the second value, or whether both are equal for sorting.
In modern Python 3, sort() and sorted()
do not directly accept a comparison function. Instead, we use
functools.cmp_to_key().
cmp means comparison.
cmp_to_key() converts a comparison function into a key function.
How a comparison function works
| Return Value | Meaning |
|---|---|
negative number |
First value should come before second value. |
0 |
Both values are equal for sorting. |
positive number |
First value should come after second value. |
Example 1: Sort numbers using a comparison function
from functools import cmp_to_key
def compare(a, b):
return a - b
numbers = [40, 10, 30, 20]
numbers.sort(key=cmp_to_key(compare))
print(numbers)
Output:
[10, 20, 30, 40]
Here compare(a, b) returns a - b.
If a is smaller, the answer is negative, so a
comes before b.
Example 2: Descending order using a comparison function
from functools import cmp_to_key
def compare(a, b):
return b - a
numbers = [40, 10, 30, 20]
numbers.sort(key=cmp_to_key(compare))
print(numbers)
Output:
[40, 30, 20, 10]
This time we return b - a.
So bigger numbers come first.
Example 3: Write comparison clearly using if-else
from functools import cmp_to_key
def compare(a, b):
if a < b:
return -1
elif a > b:
return 1
else:
return 0
numbers = [5, 2, 9, 1]
answer = sorted(numbers, key=cmp_to_key(compare))
print(answer)
Output:
[1, 2, 5, 9]
Example 4: Sort strings by length using comparison function
from functools import cmp_to_key
def compare_by_length(a, b):
return len(a) - len(b)
words = ["elephant", "cat", "tiger", "ant"]
words.sort(key=cmp_to_key(compare_by_length))
print(words)
Output:
['cat', 'ant', 'tiger', 'elephant']
The words are sorted according to their lengths.
Example 5: If length is same, sort alphabetically
from functools import cmp_to_key
def compare_words(a, b):
if len(a) != len(b):
return len(a) - len(b)
if a < b:
return -1
elif a > b:
return 1
else:
return 0
words = ["dog", "cat", "elephant", "ant", "tiger"]
words.sort(key=cmp_to_key(compare_words))
print(words)
Output:
['ant', 'cat', 'dog', 'tiger', 'elephant']
First Python compares length. If two words have the same length, Python compares them alphabetically.
Example 6: Sort by last character
from functools import cmp_to_key
def compare_last_char(a, b):
if a[-1] < b[-1]:
return -1
elif a[-1] > b[-1]:
return 1
else:
return 0
words = ["banana", "apple", "mango", "grapes"]
words.sort(key=cmp_to_key(compare_last_char))
print(words)
Output:
['banana', 'apple', 'mango', 'grapes']
The sorting is based on the last character of each word.
Example 7: Sort students by marks using comparison function
from functools import cmp_to_key
students = [
{"name": "Amit", "marks": 70},
{"name": "Ravi", "marks": 90},
{"name": "Zoya", "marks": 85},
{"name": "Meena", "marks": 60}
]
def compare_students(a, b):
return a["marks"] - b["marks"]
students.sort(key=cmp_to_key(compare_students))
print(students)
Output:
[
{'name': 'Meena', 'marks': 60},
{'name': 'Amit', 'marks': 70},
{'name': 'Zoya', 'marks': 85},
{'name': 'Ravi', 'marks': 90}
]
Example 8: Sort students by highest marks first
from functools import cmp_to_key
students = [
{"name": "Amit", "marks": 70},
{"name": "Ravi", "marks": 90},
{"name": "Zoya", "marks": 85},
{"name": "Meena", "marks": 60}
]
def compare_students(a, b):
return b["marks"] - a["marks"]
students.sort(key=cmp_to_key(compare_students))
print(students)
Output:
[
{'name': 'Ravi', 'marks': 90},
{'name': 'Zoya', 'marks': 85},
{'name': 'Amit', 'marks': 70},
{'name': 'Meena', 'marks': 60}
]
Example 9: Marks high to low, name A to Z if marks are same
from functools import cmp_to_key
students = [
{"name": "Ravi", "marks": 90},
{"name": "Amit", "marks": 70},
{"name": "Zoya", "marks": 90},
{"name": "Meena", "marks": 70}
]
def compare_students(a, b):
if a["marks"] != b["marks"]:
return b["marks"] - a["marks"]
if a["name"] < b["name"]:
return -1
elif a["name"] > b["name"]:
return 1
else:
return 0
students.sort(key=cmp_to_key(compare_students))
for student in students:
print(student["name"], student["marks"])
Output:
Ravi 90
Zoya 90
Amit 70
Meena 70
This is a powerful example. First the students are sorted by marks from high to low. If marks are equal, names are sorted alphabetically.
Example 10: Sort products by price ascending and rating descending
from functools import cmp_to_key
products = [
{"name": "Keyboard", "price": 800, "rating": 4.5},
{"name": "Mouse", "price": 500, "rating": 4.2},
{"name": "Monitor", "price": 800, "rating": 4.8},
{"name": "USB Cable", "price": 200, "rating": 4.0}
]
def compare_products(a, b):
if a["price"] != b["price"]:
return a["price"] - b["price"]
if a["rating"] > b["rating"]:
return -1
elif a["rating"] < b["rating"]:
return 1
else:
return 0
products.sort(key=cmp_to_key(compare_products))
for product in products:
print(product["name"], product["price"], product["rating"])
Output:
USB Cable 200 4.0
Mouse 500 4.2
Monitor 800 4.8
Keyboard 800 4.5
Comparison Function vs Key Function
| Feature | Key Function | Comparison Function |
|---|---|---|
| Main idea | Give one value for each item. | Compare two items at a time. |
| Used directly in Python 3? | Yes | No, needs cmp_to_key(). |
| Usually faster? | Yes | Usually slower. |
| Best for | Simple sorting rules. | Complex custom comparison logic. |
Same sorting using key function
students = [
{"name": "Ravi", "marks": 90},
{"name": "Amit", "marks": 70},
{"name": "Zoya", "marks": 90},
{"name": "Meena", "marks": 70}
]
students.sort(key=lambda student: (-student["marks"], student["name"]))
for student in students:
print(student["name"], student["marks"])
Output:
Ravi 90
Zoya 90
Amit 70
Meena 70
key.
Use a comparison function only when the sorting rule is easier to express
by comparing two items directly.
Cheat Sheet for Comparison Function
from functools import cmp_to_key
def compare(a, b):
if a < b:
return -1
elif a > b:
return 1
else:
return 0
items.sort(key=cmp_to_key(compare))
10. Sorting List of Dictionaries
Real data often comes as dictionaries. For example, each student can be a dictionary.
students = [
{"name": "Amit", "marks": 70},
{"name": "Ravi", "marks": 90},
{"name": "Zoya", "marks": 85},
{"name": "Meena", "marks": 60}
]
students.sort(key=lambda student: student["marks"])
print(students)
Output:
[
{'name': 'Meena', 'marks': 60},
{'name': 'Amit', 'marks': 70},
{'name': 'Zoya', 'marks': 85},
{'name': 'Ravi', 'marks': 90}
]
Sort by name
students.sort(key=lambda student: student["name"])
print(students)
Sort by marks from highest to lowest
students.sort(key=lambda student: student["marks"], reverse=True)
print(students)
11. Sorting by Multiple Rules
Sometimes one rule is not enough. Suppose two students have the same marks. Then we may want to sort by marks first and name second.
students = [
("Ravi", 90),
("Amit", 70),
("Zoya", 90),
("Meena", 70)
]
students.sort(key=lambda student: (student[1], student[0]))
print(students)
Output:
[('Amit', 70), ('Meena', 70), ('Ravi', 90), ('Zoya', 90)]
Python first sorts by student[1], which is marks.
If marks are equal, it sorts by student[0], which is name.
Marks highest first, name alphabetically second
students = [
("Ravi", 90),
("Amit", 70),
("Zoya", 90),
("Meena", 70)
]
students.sort(key=lambda student: (-student[1], student[0]))
print(students)
Output:
[('Ravi', 90), ('Zoya', 90), ('Amit', 70), ('Meena', 70)]
student[1] makes marks sort in descending order.
Names still sort in ascending order.
12. Sorting Objects
In Object Oriented Programming, we may have a list of objects. We can sort objects using their attributes.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __repr__(self):
return f"{self.name}: {self.marks}"
students = [
Student("Amit", 70),
Student("Ravi", 90),
Student("Zoya", 85),
Student("Meena", 60)
]
students.sort(key=lambda student: student.marks)
print(students)
Output:
[Meena: 60, Amit: 70, Zoya: 85, Ravi: 90]
Sort objects by name
students.sort(key=lambda student: student.name)
print(students)
Sort objects using comparison function
from functools import cmp_to_key
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __repr__(self):
return f"{self.name}: {self.marks}"
students = [
Student("Amit", 70),
Student("Ravi", 90),
Student("Zoya", 85),
Student("Meena", 60)
]
def compare_students(a, b):
return b.marks - a.marks
students.sort(key=cmp_to_key(compare_students))
print(students)
Output:
[Ravi: 90, Zoya: 85, Amit: 70, Meena: 60]
13. Common Mistakes
| Mistake | Problem | Correct Way |
|---|---|---|
numbers = numbers.sort() |
sort() returns None. |
numbers.sort() |
Forgetting reverse=True |
List sorts smallest to largest. | numbers.sort(reverse=True) |
| Sorting mixed types | Python cannot compare numbers and strings directly. | Convert all values to same type first. |
| Wrong dictionary key | KeyError |
Use the exact key name. |
| Using comparison function directly | Python 3 does not accept old-style comparison functions directly. | Use cmp_to_key(compare). |
Example of mixed type problem
items = [10, "5", 2]
# This will give an error:
# items.sort()
Fix
items = [10, "5", 2]
items.sort(key=int)
print(items)
Output:
[2, '5', 10]
14. Sorting Without Built-in Functions
Beginners should also understand how sorting works internally. Here is a simple bubble sort example.
numbers = [5, 2, 9, 1]
n = len(numbers)
for i in range(n):
for j in range(0, n - 1):
if numbers[j] > numbers[j + 1]:
numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
print(numbers)
Output:
[1, 2, 5, 9]
sort() or sorted().
But learning manual sorting helps you understand comparison, loops, and swapping.
15. Full Revision Program
from functools import cmp_to_key
numbers = [45, 12, 90, 33, 7]
print("Original:", numbers)
print("Using sorted:", sorted(numbers))
print("Original still same:", numbers)
numbers.sort()
print("After sort:", numbers)
numbers.sort(reverse=True)
print("Descending:", numbers)
names = ["banana", "Apple", "mango", "Cherry"]
print("Normal string sort:", sorted(names))
print("Case-insensitive sort:", sorted(names, key=str.lower))
students = [
{"name": "Amit", "marks": 70},
{"name": "Ravi", "marks": 90},
{"name": "Zoya", "marks": 85},
{"name": "Meena", "marks": 60}
]
print("Students by marks:")
print(sorted(students, key=lambda s: s["marks"]))
print("Students by marks high to low:")
print(sorted(students, key=lambda s: s["marks"], reverse=True))
def compare_students(a, b):
if a["marks"] != b["marks"]:
return b["marks"] - a["marks"]
if a["name"] < b["name"]:
return -1
elif a["name"] > b["name"]:
return 1
else:
return 0
print("Students using comparison function:")
answer = sorted(students, key=cmp_to_key(compare_students))
print(answer)
16. Practice Questions
Beginner Level
- Create a list of 5 numbers and sort it in ascending order.
- Create a list of 5 numbers and sort it in descending order.
- Create a list of names and sort it alphabetically.
- Use
sorted()and prove that the original list does not change.
Intermediate Level
- Sort words by their length.
- Sort names without caring about capital and small letters.
- Sort a list of tuples by the second value.
- Sort students by marks from highest to lowest.
Comparison Function Practice
- Sort numbers in ascending order using a comparison function.
- Sort numbers in descending order using a comparison function.
- Sort words by length using a comparison function.
- Sort words by last character using a comparison function.
- Sort students by marks descending and name ascending.
- Sort products by price ascending and rating descending.
Advanced Level
- Sort a list of dictionaries by price.
- Sort products by rating first and price second.
- Create a class
Bookwith title and price. Sort books by price. - Write bubble sort manually for a list of numbers.
17. Mini Project: Leaderboard Sorting
Let us create a small leaderboard. We want the highest score first. If two players have the same score, we sort names alphabetically.
Using key function
players = [
{"name": "Amit", "score": 120},
{"name": "Ravi", "score": 300},
{"name": "Zoya", "score": 250},
{"name": "Meena", "score": 300}
]
leaderboard = sorted(
players,
key=lambda player: (-player["score"], player["name"])
)
for rank, player in enumerate(leaderboard, start=1):
print(rank, player["name"], player["score"])
Output:
1 Meena 300
2 Ravi 300
3 Zoya 250
4 Amit 120
Using comparison function
from functools import cmp_to_key
players = [
{"name": "Amit", "score": 120},
{"name": "Ravi", "score": 300},
{"name": "Zoya", "score": 250},
{"name": "Meena", "score": 300}
]
def compare_players(a, b):
if a["score"] != b["score"]:
return b["score"] - a["score"]
if a["name"] < b["name"]:
return -1
elif a["name"] > b["name"]:
return 1
else:
return 0
leaderboard = sorted(players, key=cmp_to_key(compare_players))
for rank, player in enumerate(leaderboard, start=1):
print(rank, player["name"], player["score"])
Output:
1 Meena 300
2 Ravi 300
3 Zoya 250
4 Amit 120
18. Final Cheat Sheet
| Task | Code |
|---|---|
| Sort original list | numbers.sort() |
| Create new sorted list | new_list = sorted(numbers) |
| Descending order | numbers.sort(reverse=True) |
| Sort by length | words.sort(key=len) |
| Case-insensitive sort | sorted(words, key=str.lower) |
| Sort tuple by second item | items.sort(key=lambda x: x[1]) |
| Sort dictionary by marks | students.sort(key=lambda s: s["marks"]) |
| Sort object by attribute | students.sort(key=lambda s: s.marks) |
| Use comparison function | items.sort(key=cmp_to_key(compare)) |
Comparison Function Template
from functools import cmp_to_key
def compare(a, b):
if a < b:
return -1
elif a > b:
return 1
else:
return 0
items.sort(key=cmp_to_key(compare))
19. Practice in the Python Editor
Try the examples above in the embedded Python editor. Change the numbers, names, marks, and sorting rules.