TalentJR

🐍 Python for kids · Class 7 · Lesson 11 of 18 · Free

Sorting Data – sort(), sorted() and Key Functions

⏱ About 30 minutes · ▶ run real Python here — nothing to install · no sign-in

In this lesson you will

  • Choose between sort() and sorted(), and sort in reverse order.
  • Sort words correctly, even with capital letters, using a key.
  • Sort dictionaries and lists of records with your own key function.

On results day, everyone asks: who came first? A sorted list answers in a second. Today you will sort marks, names, dictionaries and whole student records.

What is the difference between sort() and sorted() in Python?

sort() is a list method. It changes the list itself and gives back nothing.

sorted() is a function. It leaves the old list alone and returns a new sorted list.

Use sorted() when you still need the original order, for example the order students joined.

🎬 How Python thinks — step 1 of 7Python is about to run line 1
▶marks = [72, 95, 64, 88]
2ranked = sorted(marks)
3print("Original:", marks)
4print("Sorted copy:", ranked)
5marks.sort()
6print("After sort():", marks)
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
Original: [72, 95, 64, 88]
Sorted copy: [64, 72, 88, 95]
After sort(): [64, 72, 88, 95]

💡 sorted() also works on strings, tuples and dictionaries. sort() works only on lists.

How do I sort from biggest to smallest?

Add reverse=True to either sort() or sorted(). The order is flipped, biggest first.

With a slice, you can then take the top few. [:3] gives the first three items.

This is how a leaderboard shows the top three scores.

🎬 How Python thinks — step 1 of 6Python is about to run line 1
▶runs = [45, 102, 8, 67, 33]
2high_first = sorted(runs, reverse=True)
3print(high_first)
4top3 = high_first[:3]
5print("Top 3 scores:", top3)
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
[102, 67, 45, 33, 8]
Top 3 scores: [102, 67, 45]

How does Python sort words with capital letters?

Words are sorted letter by letter, like a dictionary. But all capital letters come before small letters.

So "Zoya" comes before "anil", which looks wrong to us.

key=str.lower tells Python to compare the small-letter version. The words themselves do not change.

🐍 Python — you can edit this code
Output
['Bilal', 'Zoya', 'anil', 'meera']
['anil', 'Bilal', 'meera', 'Zoya']

💡 A key is a function. Python calls it on every item and sorts by the answers.

How do I sort with a key function?

key= can be any function that takes one item and returns something to compare.

key=len sorts words by length. You can also write your own function with def.

Write the function name without brackets. Python will call it for you, once per item.

🎬 How Python thinks — step 1 of 10Python is about to run line 1
▶def last_digit(n):
2 return n % 10
3
4nums = [23, 41, 18, 7]
5print(sorted(nums, key=last_digit))
6words = ["banana", "fig", "kiwi"]
7print(sorted(words, key=len))
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
[41, 23, 7, 18]
['fig', 'kiwi', 'banana']

💡 Items with the same key keep their old order. This is called a stable sort.

How do I sort a dictionary by keys or by values?

A dictionary has no sort() method. But sorted(scores.items()) gives a sorted list of (key, value) pairs.

By default the pairs are sorted by key. To sort by value, use a key function that returns pair[1].

With enumerate() from the last lesson, we can print a ranked list.

🐍 Python — you can edit this code
Output
['Anu', 'Dev', 'Riya']
[('Anu', 78), ('Dev', 95), ('Riya', 88)]
1. Dev    95
2. Riya   88
3. Anu    78

💡 sorted(scores) on its own gives only the keys, in order.

How do I sort a list of dictionaries?

Real data is often a list of records, like students with a name, class and marks.

Write a key function that picks the field you want, such as s["marks"].

In Lesson 14 you will learn lambda, a shorter way to write such tiny key functions.

🐍 Python — you can edit this code
Output
Isha 93
Kabir 81
Ravi 67

🤔 Predict the output

Think like Python: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

nums = [3, 1, 2]
new = sorted(nums)
print(nums, new)

Question 2. What does this print?

print(sorted(["mango", "Kiwi", "apple"]))

Question 3. What does this print?

print(sorted(["pear", "fig", "banana"], key=len, reverse=True))

🧩 Your challenge

On sports day, a dictionary stores each runner's 100 m time in seconds. The fastest time wins. Sort the runners by time, smallest first, and print the top three with Gold, Silver and Bronze.

Expected output :
Gold: Sana (13.5 s)
Silver: Diya (13.8 s)
Bronze: Aarav (14.2 s)
🐍 Python — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

marks = [50, 20, 40]
marks = marks.sort()
print(marks)

No error message – but it prints None instead of the sorted list.

✅ Right

marks = [50, 20, 40]
marks.sort()
print(marks)

sort() changes the list and returns None. Saving that None back into marks loses your list.

❌ Wrong

ages = [12, "11", 13]
print(sorted(ages))

TypeError: '<' not supported between instances of 'str' and 'int'

✅ Right

ages = [12, 11, 13]
print(sorted(ages))

Python cannot compare text with numbers. Make every item the same type, often with int().

❌ Wrong

scores = {"Riya": 88, "Dev": 95}
scores.sort()
print(scores)

AttributeError: 'dict' object has no attribute 'sort'

✅ Right

scores = {"Riya": 88, "Dev": 95}
print(sorted(scores.items()))

Only lists have sort(). For a dictionary, use sorted() on items(), which returns a new list.

📌 Remember

  • sort() changes a list in place and returns None.
  • sorted() returns a new sorted list and works on any collection.
  • reverse=True puts the biggest or last item first.
  • Capital letters sort before small letters; key=str.lower fixes that.
  • key= takes a function, like len or your own def, to choose what to compare.
  • sorted(d.items(), key=...) sorts a dictionary by key or value.

Finished the quiz and the challenge?

Questions students ask

Should I use sort() or sorted()?

Use sorted() if you need the original order later, or if the data is not a list. Use sort() to save memory on a big list.

Why does my key function have no brackets after it?

You hand Python the function itself, not its answer. Python then calls it once for each item.

How do I sort a dictionary by value from highest to lowest?

Use sorted(d.items(), key=get_value, reverse=True), where get_value returns pair[1].

Can I sort by two things, like marks and then name?

Yes. Make the key function return a tuple, like (marks, name). Python compares the first part, then the second.