Python Sorting Lists
Table of Contents
In the last lesson, we learned about Python Nested Lists. Now let’s put list items in the order we want.
Let’s Talk About Putting Things in Order
We have a list. Maybe it is a list of numbers. Maybe it is a list of names. Maybe it is a list of scores.
And we want to sort them. Put them in order. From smallest to largest. Or from A to Z. Or maybe the other way around.
That is what sorting is for. And Python makes it easy.
We have two main ways to sort a list.
sorted()— returns a new sorted list. The original is unchanged..sort()— sorts the list in place. The original is changed.
Let’s go through both.
The sorted() Function in Python
sorted() is a built-in function. It takes any iterable and returns a new list with the items sorted.
numbers = [5, 2, 9, 1, 7]sorted_numbers = sorted(numbers)print(sorted_numbers)Output
[1, 2, 5, 7, 9]The original list numbers is still [5, 2, 9, 1, 7]. Because sorted() does not change it.
We can also use it directly without assigning.
print(sorted([3, 1, 4, 1, 5, 9, 2, 6]))Output
[1, 1, 2, 3, 4, 5, 6, 9]It works on strings too.
fruits = ["banana", "apple", "cherry"]print(sorted(fruits))Output
['apple', 'banana', 'cherry']It sorts alphabetically by default. Uppercase letters come before lowercase. So "Apple" would come before "apple" if mixed.
The sort() Method in Python
.sort() is a method that belongs to lists. It sorts the list in place. It does not return a new list. It returns None.
numbers = [5, 2, 9, 1, 7]numbers.sort()print(numbers)Output
[1, 2, 5, 7, 9]Now the original list is sorted. That is the main difference.
If we try to assign the result, we get None.
numbers = [5, 2, 9, 1, 7]result = numbers.sort()print(result)Output
NoneSo let’s not assign the result of .sort(). Just call it.
Sorting in Reverse in Python
Both sorted() and .sort() accept a reverse parameter. Set it to True to sort in descending order.
numbers = [5, 2, 9, 1, 7]print(sorted(numbers, reverse=True))Output
[9, 7, 5, 2, 1]numbers = [5, 2, 9, 1, 7]numbers.sort(reverse=True)print(numbers)Output
[9, 7, 5, 2, 1]Sorting with a Custom Key in Python
Sometimes the default sorting is not what we want. Maybe we have a list of tuples. And we want to sort by the second item instead of the first.
That is where the key parameter comes in. We give it a function that tells Python how to extract the value to sort by.
Let’s say we have a list of names and ages.
people = [("Alex", 25), ("Sam", 30), ("John", 22)]sorted_people = sorted(people, key=lambda person: person[1])print(sorted_people)Output
[('John', 22), ('Alex', 25), ('Sam', 30)]The key=lambda person: person[1] tells Python to use the second item (the age) for sorting.
We can also sort by the first item (the name). That is the default.
print(sorted(people))Output
[('Alex', 25), ('John', 22), ('Sam', 30)]But using key gives us flexibility.
Sorting Strings by Length in Python
Let’s sort a list of words by their length.
words = ["banana", "apple", "cherry", "date"]sorted_words = sorted(words, key=len)print(sorted_words)Output
['date', 'apple', 'banana', 'cherry']len is a built-in function. It takes a string and returns its length. So key=len means sort by length.
We can combine with reverse=True to get longest first.
print(sorted(words, key=len, reverse=True))Output
['banana', 'cherry', 'apple', 'date']Sorting Case-Insensitively in Python
By default, sorting is case-sensitive. Uppercase letters come before lowercase.
words = ["banana", "Apple", "cherry"]print(sorted(words))Output
['Apple', 'banana', 'cherry']If we want case-insensitive sorting, we use key=str.lower.
words = ["banana", "apple", "Cherry", "date"]print(sorted(words, key=str.lower))Output
['apple', 'banana', 'Cherry', 'date']Now “Cherry” is sorted with the lowercase letters. Without key=str.lower, it would come first because ‘C’ is uppercase.
Sorting a List of Dictionaries in Python
We can sort a list of dictionaries by a specific key.
products = [ {"name": "Laptop", "price": 1200}, {"name": "Phone", "price": 800}, {"name": "Tablet", "price": 500}]
sorted_products = sorted(products, key=lambda p: p["price"])for product in sorted_products: print(f"{product['name']}: ${product['price']}")Output
Tablet: $500Phone: $800Laptop: $1200That is very common in real programs.
Sorting in Place vs New List in Python
We use .sort() when we do not need the original list anymore. It is slightly faster because it does not create a new list.
We use sorted() when we want to keep the original list unchanged. Or when we are working with an iterable that is not a list (like a tuple or a set).
Python Sorting Lists: A Real-Life Example
Let’s sort a list of students by their grades.
students = [ {"name": "Alex", "grade": 85}, {"name": "Sam", "grade": 92}, {"name": "John", "grade": 78}, {"name": "Emma", "grade": 95}]
# Sort by grade, highest firstsorted_students = sorted(students, key=lambda s: s["grade"], reverse=True)
for student in sorted_students: print(f"{student['name']}: {student['grade']}")Output
Emma: 95Sam: 92Alex: 85John: 78That is a typical use case.
Common Mistakes with Python Sorting Lists
Mistake 1: Assigning the Result of sort()
numbers = [3, 1, 2]numbers = numbers.sort() # numbers becomes Noneprint(numbers)Output
NoneSo what do we do? We just call numbers.sort() without assigning.
Mistake 2: Thinking sorted() Changes the Original
numbers = [3, 1, 2]sorted(numbers)print(numbers)Output
[3, 1, 2]So what do we do? We assign the result.
numbers = sorted(numbers)Mistake 3: Using the Wrong Key Function
people = [("Alex", 25), ("Sam", 30)]sorted(people, key=lambda p: p[2]) # Error! Index out of rangeSo what do we do? We use a valid index or attribute.
sorted(people, key=lambda p: p[1])Mistake 4: Forgetting That Sorting Mixed Types Fails
mixed = [1, "hello", 3]sorted(mixed) # Error!We cannot compare numbers and strings. So sorting fails.
Next, we will learn about Copying Python Lists and create independent or nested copies safely.