Advertisement
Have you ever looked at a messy list of numbers or words and wished there was a simple way to clean it up? Python makes that easy. Sorting a list isn’t just about making things look neat. It often helps improve search performance, find duplicates, or clean data before you process it. When you're working with a list in Python—whether it’s a list of names, prices, or scores—the sort() method is your go-to tool to rearrange things in order.
It's built into every list object, and it doesn't need any fancy setup. This method works in place, so it changes the list directly without making a new one. This guide will break down everything you need to know about sorting lists in Python using sort(), from basic to more advanced sorting tricks.
The sort() method is called directly on a list and, by default, sorts it in ascending order. Here's a basic example:
python
CopyEdit
numbers = [4, 1, 3, 9, 2]
numbers.sort()
print(numbers)
# Output: [1, 2, 3, 4, 9]
The original list is updated, and the numbers are now sorted. It doesn't need to be assigned to a new variable unless you also want the old order. If you wish to create a new list, use the built-in sorted() function instead.
If you want your list in descending order, pass reverse=True to sort().
python
CopyEdit
numbers = [4, 1, 3, 9, 2]
numbers.sort(reverse=True)
print(numbers)
# Output: [9, 4, 3, 2, 1]
This is useful for leaderboard scores or price listings where you want the biggest value first.
You can sort strings just as easily. By default, it sorts by Unicode values, which means uppercase letters come before lowercase ones.
python
CopyEdit
words = ["banana", "Apple", "cherry"]
words.sort()
print(words)
# Output: ['Apple', 'banana', 'cherry']
Notice how "Apple" comes before "banana" because capital letters are smaller in Unicode.
If you want a case-insensitive sort, you can use a key function. The key argument lets you define a rule for sorting.
python
CopyEdit
words = ["banana", "Apple", "cherry"]
words.sort(key=str.lower)
print(words)
# Output: ['Apple', 'banana', 'cherry']
Now it sorts everything as if it were lowercase, which feels more natural.
If your list has tuples, you can sort by a specific element in each tuple. Let’s say you have a list of students with their scores.
python
CopyEdit
students = [("John", 82), ("Emma", 91), ("Alex", 78)]
students.sort(key=lambda x: x[1])
print(students)
# Output: [('Alex', 78), ('John', 82), ('Emma', 91)]
This sorts the list by the second item in each tuple, which is the score.
If you're working with objects, you can sort them by attributes. Suppose you have a class like this:
python
CopyEdit
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
items = [Product("Pen", 1.5), Product("Notebook", 3.0), Product("Pencil", 0.5)]
items.sort(key=lambda x: x.price)
for item in items:
print(item.name, item.price)
# Output:
# Pencil 0.5
# Pen 1.5
# Notebook 3.0
This is one of the most practical uses of sort() in real-world applications like e-commerce or databases.
You can sort lists by length, too. This is useful when dealing with strings or sublists.
python
CopyEdit
names = ["Anna", "Elizabeth", "Tom", "Catherine"]
names.sort(key=len)
print(names)
# Output: ['Tom', 'Anna', 'Elizabeth', 'Catherine']
Shortest names come first. You can combine this with reverse=True to get the longest first.
If you want more control, combine the key and reverse options. For example, sort by string length in descending order:
python
CopyEdit
names = ["Anna", "Elizabeth", "Tom", "Catherine"]
names.sort(key=len, reverse=True)
print(names)
# Output: ['Catherine', 'Elizabeth', 'Anna', 'Tom']
This gives you full control over how your list is arranged.
You might think of mixing strings and numbers in one list. It can lead to errors:
python
CopyEdit
mixed = [1, "two", 3]
mixed.sort()
# Output: TypeError: '<' not supported between instances of 'str' and 'int'
The sort() method can’t compare different types unless you manually define how to handle them with a key function. But usually, it’s better to keep types consistent.
Nested lists can also be sorted by values inside. Suppose you have:
python
CopyEdit
data = [[1, 9], [2, 3], [4, 1]]
data.sort(key=lambda x: x[1])
print(data)
# Output: [[4, 1], [2, 3], [1, 9]]
It sorts by the second number in each sublist. This can be helpful when sorting structured data like CSV rows or records.
You can sort a list based on a calculated value from each item. This is useful when you want to sort based on some transformation, like the absolute value of numbers or a substring of each item.
python
CopyEdit
numbers = [-10, 3, -1, 7, -20]
numbers.sort(key=abs)
print(numbers)
# Output: [-1, 3, 7, -10, -20]
In this case, the list is sorted by absolute values instead of the original numbers. This is useful when you want to ignore the sign or sort based on a custom calculation. You can use any function in the key argument as long as it returns a value by which to sort.
Sorting lists in Python using sort() is one of the most useful and easy-to-learn tools in the language. Whether you're sorting numbers, strings, or objects, this method lets you do it quickly without extra setup. It works in place, gives you control of key functions, and can handle everything from case-insensitive sorting to arranging custom objects. The Python sort method is flexible and fast, making it ideal for everyday use in data cleaning, reporting, or just tidying up output. Once you get used to it, you'll find yourself reaching for sort() whenever you want to bring order to chaos in your code, projects, or daily data-related tasks.
Advertisement
Jio Brain by Jio Platforms brings seamless AI integration to Indian enterprises by embedding intelligence into existing systems without overhauls. Discover how it simplifies real-time data use and smart decision-making
Looking for quality data science blogs to follow in 2025? Here are the 10 most practical and insightful blogs for learning, coding, and staying ahead in the data world
Discover how Getty's Generative AI by iStock provides creators and brands with safe, high-quality commercial-use AI images.
Discover multilingual LLMs: how they handle 100+ languages, code-switching and 10 other things you need to know.
Want to build a dataset tailored to your project? Learn six ways to create your own dataset in Python—from scraping websites to labeling images manually
SAS acquires a synthetic data generator to boost AI development, improving privacy, performance, and innovation across industries
Create user personas for ChatGPT to improve AI responses, boost engagement, and tailor content to your audience.
How to use Matplotlib.pyplot.hist() in Python to create clean, customizable histograms. This guide explains bins, styles, and tips for better Python histogram plots
Learn about Inception Score (IS): how it evaluates GANs and generative AI quality via image diversity, clarity, and more.
Learn how sorting lists in Python using sort() can help organize data easily. This beginner-friendly guide covers syntax, examples, and practical tips using the Python sort method
Stay informed with the best AI news websites. Explore trusted platforms that offer real-time AI updates, research highlights, and expert insights without the noise
Learn seven methods to convert a string to an integer in Python using int(), float(), json, eval, and batch processing tools like map() and list comprehension