Python Sorting Lists
Table of Contents + −
In the last lesson you learned about Nested Lists. That is a list that holds other lists inside it. Now we have a different need. You have a list of items. You want them in order. Names from A to Z. Prices from low to high. Scores from high to low. Python gives you two clean ways to do that. This lesson shows you both.
🤔 Why Sort a List?
Picture a list of scores. You collected them one by one as players finished a game. They came in random order. Now you want a leaderboard with the highest score first. Reading through an unsorted list and putting it in order by hand is slow. It is also easy to get wrong.
Sorting fixes that. You hand Python the list. It puts the items in order for you. Python gives you two tools for this. The difference between them matters a lot.
⚖️ sort() vs sorted() — The Key Difference
Here is the one idea people most often get wrong. So let’s make it clear right away.
sort() is a method you call on the list. It changes the original list in place. It returns nothing.
sorted() is a built-in function. It leaves the original list untouched. It gives you back a brand new sorted list.
This small table makes the difference easy to remember.
| Question | sort() | sorted() |
|---|---|---|
| Is it a method or a function? | Method on the list | Built-in function |
| Does it change the original? | Yes, in place | No, original stays |
| What does it give back? | Nothing (None) | A new sorted list |
| How you call it | numbers.sort() | sorted(numbers) |
Let’s see both side by side. This code sorts the same list two ways. You can watch what happens to the original.
scores = [50, 90, 30, 70]
# sort() changes scores itself and gives back nothingresult = scores.sort()print("After sort():", scores)print("sort() returned:", result)
# sorted() works on a fresh list so we can see the differenceages = [50, 90, 30, 70]new_list = sorted(ages)print("sorted() returned:", new_list)print("ages is unchanged:", ages)Output
After sort(): [30, 50, 70, 90]sort() returned: Nonesorted() returned: [30, 50, 70, 90]ages is unchanged: [50, 90, 30, 70]Walk through what each line did:
scores.sort()reorderedscoresitself. Nowscoresis[30, 50, 70, 90].- The value it gave back was
None. That is whyresultprinted asNone. sorted(ages)built a new list and put it innew_list.agesstayed exactly as it was.sorted()never touches the original.
Caution
A common bug is writing scores = scores.sort(). Since sort() returns None, you just threw your list away and replaced it with None. Call scores.sort() on its own line, or use sorted() when you want a returned value.
So which one do you use? If you are happy changing the list you have, use sort(). If you need to keep the original as it was and also have a sorted copy, use sorted().
⬆️ Ascending and Descending Order
By default both tools sort in ascending order. That means smallest to largest for numbers, and A to Z for text. Most of the time that is exactly what you want.
When you want the other direction, you add reverse=True. That flips it to descending. So largest first, or Z to A.
This example builds that leaderboard we talked about, with the highest score first.
scores = [50, 90, 30, 70]
scores.sort(reverse=True)print("Leaderboard:", scores)Output
Leaderboard: [90, 70, 50, 30]The same reverse=True works with sorted() too, when you want a new list instead.
prices = [12, 5, 20, 8]highest_first = sorted(prices, reverse=True)
print("New sorted list:", highest_first)print("Original prices:", prices)Output
New sorted list: [20, 12, 8, 5]Original prices: [12, 5, 20, 8]🔤 Sorting Numbers and Strings
Sorting numbers is easy. Python already knows that 30 comes before 50.
Strings sort in alphabetical order. Well, almost. Python actually sorts text by character codes. Every uppercase letter comes before every lowercase letter. So "Zoe" sorts before "alex". That surprises people the first time.
This example sorts a list of names. It shows that uppercase-first behavior.
names = ["Riya", "alex", "Arjun", "bina"]print(sorted(names))Output
['Arjun', 'Riya', 'alex', 'bina']See how both capitalized names landed first? If you want a sort that ignores case, you can tell Python to compare the lowercase version of each name. That is where a key function comes in, which is next.
Caution
You cannot sort a list that mixes numbers and strings, like [3, "two", 1]. Python does not know whether 3 should come before or after "two", so it raises a TypeError. Sort a list where all items are the same kind.
🔑 Sorting with a key Function
Sometimes plain order is not what you want. Maybe you want the shortest word first. Or you want to sort people by their age, not their name. For that you pass a key.
A key is a function. Python runs it on each item. It sorts by whatever that function gives back. The items themselves stay the same. Only the comparison value changes.
Say you want words sorted by how long they are. You give key=len, because len returns the length of each word.
words = ["banana", "kiwi", "apple", "fig"]words.sort(key=len)print(words)Output
['fig', 'kiwi', 'apple', 'banana']Python called len on every word. "fig" is 3 letters. "kiwi" is 4, and so on. So it ordered them shortest to longest.
For sorting by a field, a list of tuples is the common case. Imagine each tuple is a person as (name, age). You want them ordered youngest first. You point the key at the second item of each tuple.
people = [("Riya", 30), ("Arjun", 22), ("Alex", 27)]people.sort(key=lambda person: person[1])
for name, age in people: print(f"{name} is {age}")Output
Arjun is 22Alex is 27Riya is 30Here lambda person: person[1] is a tiny one-line function. It takes one person tuple and returns person[1], which is the age. So Python sorts the list by age. The names follow along with their ages. If you wanted oldest first, you would add reverse=True next to the key.
And remember that case-insensitive name sort from earlier? You fix it with key=str.lower, so Python compares everything in lowercase.
names = ["Riya", "alex", "Arjun", "bina"]print(sorted(names, key=str.lower))Output
['alex', 'Arjun', 'bina', 'Riya']⚠️ Common Mistakes
A few slip-ups come up again and again. Watch for these.
- Reassigning the result of
sort(). It returnsNone, so you lose your data.
# ❌ Avoid: numbers becomes Nonenumbers = [3, 1, 2]numbers = numbers.sort()
# ✅ Good: sort in place, then use numbersnumbers = [3, 1, 2]numbers.sort()- Calling the key function instead of passing it. Pass the name, do not add parentheses.
# ❌ Avoid: this calls len() with no argument and crasheswords.sort(key=len())
# ✅ Good: pass len itself, Python calls it for youwords.sort(key=len)- Trying to sort mixed types like numbers and strings together. Python raises a
TypeError. Keep the items the same kind.
✅ Best Practices
- Reach for
sorted()when you still need the original list. Usesort()only when you truly want to change the list in place. - Let
keydo the work for “sort by something”. Sort by length, by a field, or by lowercase, instead of rearranging the data yourself. - Add
reverse=Truefor descending order rather than sorting and then reversing the list by hand. - Keep every item in the list the same type, so the comparison always makes sense.
🧩 What You’ve Learned
- ✅
sort()orders the list in place and returnsNone, whilesorted()returns a new list and leaves the original alone. - ✅ Both sort ascending by default, and
reverse=Trueswitches them to descending. - ✅ Numbers sort by value, and strings sort alphabetically with uppercase letters coming before lowercase.
- ✅ A
keyfunction lets you sort by length, by a tuple field, or case-insensitively. - ✅ Reassigning
sort(), calling the key with parentheses, and mixing types are the usual mistakes to avoid.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does the sort() method return?
Why: sort() changes the list in place and returns None, so you should never reassign its result.
- 2
You need to keep the original list and also have a sorted version. Which do you use?
Why: sorted() builds a new list and leaves the original untouched, which is exactly what you need here.
- 3
How do you sort a list of numbers from largest to smallest?
Why: reverse=True flips the order to descending, giving you largest first.
- 4
Which call sorts a list of words by their length?
Why: You pass the function len itself as the key, and Python calls it on each word to compare by length.
🚀 What’s Next?
You now know how to put list items in order. Next we look at a tricky part of lists that surprises many people. It is how to make a real copy of a list instead of accidentally sharing the same one.