How to sort a list in Python
Sorting is a fundamental operation in programming that helps organize data in a meaningful order, making it easier to search, analyze, and process. Python provides straightforward and flexible methods for sorting lists, making it a powerful tool for managing ordered data. In this tutorial, we will learn how to sort a list in Python, different ways of customizing the sorting, and real-world list sorting techniques.
Python provides two built-in methods for sorting lists: sort()
and sorted()
. Let’s explore how these sorting methods work.
How does .sort()
work?
The .sort()
method sorts a list in place, meaning it directly modifies the original list instead of creating a new one. This method is best used when we do not need to preserve the original order of elements.
In-place sorting with .sort()
The .sort()
method sorts list in place, modifying the original list instead of creating a new one. Let’s see how it works with an example.
numbers = [8, 3, 1, 6, 2, 9]numbers.sort()print(numbers)
The output will be:
[1, 2, 3, 6, 8, 9]
The elements in a list are now permanently sorted in ascending order.
Learn Sorting Algorithms with Python
Learn about the usefulness and efficiency of computational sorting by implementing different sorting algorithms yourself.Try it for freeSort a list in descending order using .sort()
To sort the list in descending order, we use the reverse=True
parameter. For example:
numbers = [8, 3, 1, 6, 2, 9]numbers.sort(reverse=True)print(numbers)
The code will result in the following output:
[9, 8, 6, 3, 2, 1]
This reverses the order of elements, sorting them from highest to lowest.
How to sort a list using sorted()
Unlike .sort()
, the sorted()
function creates a new sorted list without changing the original one. This is useful when we need both the sorted and unsorted versions.
Creating new sorted lists
In the following example, sorted_numbers
holds the sorted version of numbers
, but the original list stays the same. Since sorted()
creates a new sorted list without changing the original, it’s useful when we need a sorted list while keeping the original order intact.
numbers = [8, 3, 1, 6, 2, 9]sorted_numbers = sorted(numbers)print(sorted_numbers)print(numbers)
Here is the output:
[1, 2, 3, 6, 8, 9] # sorted_numbers[8, 3, 1, 6, 2, 9] # numbers (original list remains unchanged)
Sort a list in descending order using sorted()
Like .sort()
, the sorted()
function also accepts reverse=True
to sort a list in descending order:
numbers = [8, 3, 1, 6, 2, 9]sorted_numbers = sorted(numbers, reverse=True)print(sorted_numbers)
Here is the output:
[9, 8, 6, 3, 2, 1]
Differences between .sort()
and sorted()
Here are the key differences between the functions .sort()
and sorted()
:
Feature | .sort() |
sorted() |
---|---|---|
Modifies original list? | Yes | No |
Returns a new list? | No (None) | Yes |
Works on all iterables? | No (only lists) | Yes (lists, tuples, etc.) |
Best for? | When modifying the original list is acceptable | When the original list must be preserved |
So far, we’ve learned how to sort lists using Python’s built-in methods. But what if we need to sort elements based on a specific attribute instead of the default order? This is where customization comes into play.
Python allows us to customize sorting behavior using the key
parameter to define how elements should be compared. We can also modify sorting logic using lambda functions, named functions, and the operator
module. Let’s understand these different ways to customize sorting.
Custom sorting using key
parameter
The key
parameter specifies a function that extracts a value for sorting. Instead of sorting items directly, Python sorts them based on the values returned by this function. In the following example, key=len
sorts the words based on their length, from shortest to longest:
words = ["apple", "banana", "kiwi", "cherry"]sorted_words = sorted(words, key=len)print(sorted_words)
The output will be:
['kiwi', 'apple', 'banana', 'cherry']
We can see in the output that “kiwi” (4 letters) comes first, followed by “apple” (5 letters), “banana” (6 letters), and “cherry” (6 letters). If two words have the same length, they maintain their original order.
Custom sorting using lambda function
Lambda functions are small, anonymous functions often used for short operations. They allow us to define a function in a single line without using the def
keyword. Lambda functions are useful for concisely defining custom sorting criteria.
The general syntax of a lambda function is:
lambda arguments: expression
When used with sorted()
, a lambda function allows us to specify exactly how items should be sorted by defining a custom key.
For example: lambda x: abs(x)
extracts the absolute value of each number for sorting.
numbers = [-10, 5, -3, 2, -7]sorted_numbers = sorted(numbers, key=lambda x: abs(x))print(sorted_numbers)
Following is the output:
[2, -3, 5, -7, -10]
Lambda functions are not limited to numbers. They can be used to sort strings based on length.
words = ["banana", "fig", "apple", "kiwi"]sorted_words = sorted(words, key=lambda x: len(x))print(sorted_words)
Here is the output:
['fig', 'kiwi', 'apple', 'banana']
Here, lambda x: len(x)
extracts the length of each word and sorts accordingly.
Custom sorting using named functions
While lambda functions are great for short operations, they can sometimes make the code harder to read—especially when the sorting logic is complex. A named function provides better readability, maintainability, and reusability, making the code more understandable. Instead of writing an anonymous function inline, we can define a separate function and pass it as the key
parameter to sorted()
.
For example, we have a list of words and want to sort them based on their last letter instead of the default alphabetical order. We define a new named function called last_char
to extract the last character of the word.
def last_char(word):return word[-1]# List of words to sortwords = ["apple", "banana", "kiwi", "cherry"]# Sort words using the last character as the sorting keysorted_words = sorted(words, key=last_char)print(sorted_words)
The output will be:
['banana', 'apple', 'kiwi', 'cherry']
In this code, the last_char()
function extracts the last character of a word using word[-1]
, and the sorted()
function sorts the words based on this extracted character.
Sorting with the operator
module
The operator
module provides built-in functions that make sorting operations cleaner and more efficient. It is particularly useful when sorting lists of dictionaries, objects, or tuples by a specific field. Instead of using lambda functions, the operator
module offers functions like:
operator.itemgetter()
: For sorting dictionaries and lists by a specific key or index.operator.attrgetter()
: For sorting objects by attributes.
Let’s say we have a list of students represented as dictionaries. We want to sort them by age in ascending order. Using operator.itemgetter()
, we can sort a list of dictionaries according to the age of the students:
import operatorstudents = [{"name": "Alice", "age": 25},{"name": "Bob", "age": 22},{"name": "Charlie", "age": 23}]# Sorting using itemgettersorted_students = sorted(students, key=operator.itemgetter("age"))print(sorted_students)
The output will be:
[{'name': 'Bob', 'age': 22},{'name': 'Charlie', 'age': 23},{'name': 'Alice', 'age': 25}]
Sorting isn’t just about arranging numbers or strings. It is essential for data processing, user interface displays, and organizing complex data structures such as objects and dictionaries.
In the next section, we’ll walk through common sorting scenarios, including sorting strings and numbers, while addressing case sensitivity, natural sorting, and multi-criteria sorting.
Common sorting scenarios and solutions
Different types of data require different sorting techniques. Let’s explore practical sorting use cases and how to implement them in Python.
Case-sensitive vs. case-insensitive sorting
When sorting strings, case sensitivity can impact the order in which words appear. Python’s default sorting behavior is case-sensitive, meaning that uppercase letters come before lowercase due to their ASCII values.
Let’s compare the default sorting behavior with a case-insensitive approach:
words = ["banana", "apple", "Cherry", "date"]sorted_case_sensitive = sorted(words)print(sorted_case_sensitive)
The output will be:
['Cherry', 'apple', 'banana', 'date']
Sorting without any modifications results in uppercase letters appearing first due to ASCII values.
To ignore case differences, we use key=str.lower
. This ensures all words are treated as lowercase during sorting while keeping their original capitalization in the output.
words = ["banana", "apple", "Cherry", "date"]sorted_case_insensitive = sorted(words, key=str.lower)print(sorted_case_insensitive)
Here is the output:
['apple', 'banana', 'Cherry', 'date']
Sorting numbers in strings correctly
When sorting file names, version numbers, or any data containing numbers within strings, default lexicographical sorting does not always produce the expected order.
Example of incorrect sorting:
files = ["file10.txt", "file2.txt", "file1.txt"]print(sorted(files))
The output will be:
['file1.txt', 'file10.txt', 'file2.txt'] # Incorrect order
Since numbers are compared digit by digit in lexicographical sorting, “10” appears before “2” because “1” is smaller than “2”. This does not reflect natural numerical order.
To sort naturally, we use natsort
:
from natsort import natsortedfiles = ["file10.txt", "file2.txt", "file1.txt"]print(natsorted(files))
The output will be:
['file1.txt', 'file2.txt', 'file10.txt']
Note: You’ll need to install
natsort
to use it.
Sorting floating-point numbers
Floating-point numbers can also be sorted in the same way as integers:
floats = [3.2, 1.5, 4.8, 2.0]sorted_floats = sorted(floats)print(sorted_floats)
Here is the output:
[1.5, 2.0, 3.2, 4.8]
If sorting a mix of integers and floats, Python handles it automatically:
mixed_numbers = [3, 1.2, 5.7, 2, 4]print(sorted(mixed_numbers))
The output will be:
[1.2, 2, 3, 4, 5.7]
Sorting by multiple attributes
What if two people are the same age? We use a tuple in the key
function. Python sorts by the first element in the tuple first, and if there’s a tie, it moves to the second element.
class Person:def __init__(self, name, age):self.name = nameself.age = agedef __repr__(self):return f"{self.name} ({self.age})"people = [Person("Alice", 30),Person("Bob", 25),Person("Charlie", 30),Person("Dave", 25)]sorted_people = sorted(people, key=lambda p: (p.age, p.name)) then nameprint(sorted_people)
The output will be:
[Bob (25), Dave (25), Alice (30), Charlie (30)]
The key=lambda p: (p.age, p.name)
ensures:
- People are first sorted by age.
- Two people of the same age are sorted alphabetically by name.
Bob and Dave, both 25 years old, are sorted alphabetically (Bob comes first). Similarly, Alice and Charlie, both 30 years old, are sorted alphabetically (Alice comes first).
Conclusion
In this tutorial, we learned:
- Python offers two built-in sorting methods:
.sort()
(modifies the original list) andsorted()
(returns a new sorted list). - The
key
parameter allows customization of sorting behavior using lambda functions, named functions, or the operator module. - Sorting can be applied to different data types, including numbers, strings, lists of dictionaries, and custom objects.
- Case sensitivity, numeric sorting in strings, and multi-criteria sorting are essential considerations for real-world applications.
If you want to learn more about lists in Python and how they work, then you can take Codecademy’s free course on Python 3.
Author
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
How to Sort Lists of Lists in Python with Examples
Learn how to sort lists of lists in Python. Explore simple to advanced methods, including, `sorted()`, `map()`, and multi-criteria sorting for complex data. - Article
How to Sort a Dictionary by Key or Value in Python
Learn how to sort Python dictionaries by values or keys. In this tutorial, we'll cover built-in functions like `sorted()` and `dict.items()` to help you sort dictionaries in ascending or descending order and handle edge cases using `OrderedDict`. - Article
Sorting and Unary Operations in NumPy
Explore sorting and unary operations in NumPy arrays with examples for single and multi-dimensional data.
Learn more on Codecademy
- Course
Learn Sorting Algorithms with Python
Learn about the usefulness and efficiency of computational sorting by implementing different sorting algorithms yourself.With CertificateIntermediate3 hours - Free course
Java: Algorithms
Learn the basics of recursion and how to implement and analyze important algorithms in Java.Beginner Friendly3 hours - Free course
Getting Started with Python for Data Science
Work hands-on with real datasets while learning Python for data science.Beginner Friendly7 hours