How to Sort a List in Python
What you’ll build or solve
You’ll sort a Python list in ascending or descending order, including sorting text, numbers, and lists of dictionaries.
When this approach works best
This approach works best when you:
Learn Python on Mimo
- Need to display items in a predictable order, like prices low-to-high or names A-to-Z.
- Want to rank or pick top results, like highest scores or most recent dates.
- Have structured data and need to sort by a specific field, like sorting a list of users by age.
Avoid this approach when:
- You need to preserve the original order and only filter items. Sorting changes order, so filter first or copy the list.
Prerequisites
- Python installed
- You know what a list is
Step-by-step instructions
1) Pick sort() or sorted() based on whether you want to change the list
Python gives you two main ways to sort:
my_list.sort()sorts the list in place and returnsNone.sorted(my_list)returns a new sorted list and keeps the original unchanged.
numbers= [3,1,2]
numbers.sort()
print(numbers)
Using sorted():
numbers= [3,1,2]
sorted_numbers=sorted(numbers)
print(sorted_numbers)
print(numbers)
What to look for: if you do result = numbers.sort(), result becomes None.
2) Sort in descending order
Use reverse=True to sort from largest to smallest, or Z-to-A for text.
scores= [10,5,25,7]
scores.sort(reverse=True)
print(scores)
With sorted():
scores= [10,5,25,7]
top_first=sorted(scores,reverse=True)
print(top_first)
3) Sort text with consistent casing
String sorting is case-sensitive, so uppercase letters can come before lowercase letters. For a more natural alphabetical sort, use key=str.lower.
names= ["mina","Sam","ada","Zoe"]
names_sorted=sorted(names)
print(names_sorted)
Case-insensitive sort:
names= ["mina","Sam","ada","Zoe"]
names_sorted=sorted(names,key=str.lower)
print(names_sorted)
What to look for: using key=str.lower does not change the strings, it only changes how Python compares them.
4) Sort by a custom rule with key=
The key function tells Python what value to sort by.
Sort by length:
words= ["python","go","javascript","c"]
print(sorted(words,key=len))
Sort by absolute value:
values= [-10,3,-2,7]
print(sorted(values,key=abs))
5) Sort lists of dictionaries by a field
A common real-world case is sorting records by a specific key like age, price, or created_at.
users= [
{"name":"Mina","age":34},
{"name":"Sam","age":27},
{"name":"Ada","age":30},
]
by_age=sorted(users,key=lambdau:u["age"])
print(by_age)
If a key might be missing, sort more safely with get() and a default:
users= [
{"name":"Mina","age":34},
{"name":"Sam"},
{"name":"Ada","age":30},
]
by_age=sorted(users,key=lambdau:u.get("age",0))
print(by_age)
What to look for: if you sort with u["age"] and one item has no age, you get a KeyError.
Examples you can copy
Example 1: Sort numbers and keep the original list
numbers= [12,3,9,1]
sorted_numbers=sorted(numbers)
print("sorted:",sorted_numbers)
print("original:",numbers)
Example 2: Sort names case-insensitively
names= ["mina","Sam","ada","Zoe"]
print(sorted(names,key=str.lower))
Example 3: Sort products by price, highest first
products= [
{"name":"Notebook","price":4.5},
{"name":"Pen","price":1.2},
{"name":"Backpack","price":29.0},
]
by_price_desc=sorted(products,key=lambdap:p["price"],reverse=True)
print(by_price_desc)
Example 4: Sort by two fields (primary, then secondary)
This uses a tuple to sort by city first, then by name within each city.
people= [
{"name":"Naomi","city":"Boston"},
{"name":"Sam","city":"New York"},
{"name":"Ada","city":"Los Angeles"},
]
sorted_people=sorted(
people,
key=lambdap: (p["city"],p["name"].lower())
)
print(sorted_people)
Common mistakes and how to fix them
Mistake 1: Saving the result of .sort()
You might write:
numbers= [3,1,2]
result=numbers.sort()
print(result)
Why it breaks: .sort() sorts in place and returns None.
Correct approach:
numbers= [3,1,2]
numbers.sort()
print(numbers)
numbers= [3,1,2]
result=sorted(numbers)
print(result)
Mistake 2: Sorting a list with mixed types
You might write:
items= [3,"2",1]
items.sort()
Why it breaks: Python cannot compare numbers and strings during sorting.
Correct approach: convert all items to the same type before sorting.
items= [3,"2",1]
items_clean= [int(x)ifisinstance(x,str)elsexforxinitems]
items_clean.sort()
print(items_clean)
Troubleshooting
- If you see
TypeError: '<' not supported between instances of ..., check for mixed types and convert them before sorting. - If you see
Noneafter sorting, you saved the return value of.sort(). Usesorted()or sort the list directly. - If you see
KeyErrorwhile sorting dictionaries, usedict.get("key", default)in yourkey=function. - If your sort looks wrong for text, use
key=str.lowerfor case-insensitive ordering. - If numbers sort like strings, for example
"10"before"2", convert them tointorfloatfirst.
Quick recap
- Use
list.sort()to sort in place, orsorted(list)to get a new list. - Add
reverse=Truefor descending order. - Use
key=to control how items are compared. - For dictionaries, sort with
key=lambda d: d["field"]ord.get("field", default). - Fix mixed-type issues by converting values before sorting.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot