How to sort a list in Python

Learn how to sort a list in Python. This guide covers different methods, tips, real-world applications, and how to debug common errors.

How to sort a list in Python
Published on: 
Thu
Feb 5, 2026
Updated on: 
Tue
Feb 10, 2026
The Replit Team Logo Image
The Replit Team

Sorting lists in Python is a fundamental skill for organizing data. Python’s built-in functions, like sort() and sorted(), provide simple and powerful ways to manage your data structures effectively.

You'll explore several sorting techniques with practical examples. You'll also find implementation tips, real-world applications, and debugging advice to help you choose the right approach for your needs.

Basic list sorting with sort() method

numbers = [5, 2, 8, 1, 9]
numbers.sort()
print(numbers)--OUTPUT--[1, 2, 5, 8, 9]

The sort() method modifies the list directly—an operation known as sorting in-place. This approach is memory-efficient because it doesn't create a new copy of the list, making it a great choice for large datasets. When you call numbers.sort(), the original numbers list is permanently rearranged into ascending order.

It's important to remember that sort() returns None. A common mistake is trying to assign the result to a new variable. You simply call the method on the list you want to change, and the modification happens automatically.

Common sorting techniques

While sort() modifies your list directly, you can gain more control with the sorted() function, reverse sorting, and custom keys for more complex scenarios.

Sorting with the sorted() function

original = [5, 2, 8, 1, 9]
sorted_list = sorted(original)
print("Original:", original)
print("Sorted:", sorted_list)--OUTPUT--Original: [5, 2, 8, 1, 9]
Sorted: [1, 2, 5, 8, 9]

Unlike the sort() method, the sorted() function returns a new sorted list while leaving the original untouched. This non-destructive approach is perfect when you need to preserve your initial data.

  • Because sorted() creates a new list, you must assign its output to a variable to use it, as shown with sorted_list.
  • While the sort() method only works on lists, the sorted() function can handle any iterable, like tuples or strings.

Sorting in reverse order

numbers = [5, 2, 8, 1, 9]
numbers.sort(reverse=True)
print(numbers)--OUTPUT--[9, 8, 5, 2, 1]

For descending order, simply add the reverse=True argument. This tells Python to arrange the list from the largest value to the smallest. It’s a straightforward way to flip the default ascending sort.

  • This parameter works for both the in-place sort() method and the sorted() function, which returns a new list.

Sorting with custom keys

fruits = ["apple", "banana", "cherry", "date", "elderberry"]
fruits.sort(key=len)
print(fruits)--OUTPUT--['date', 'apple', 'cherry', 'banana', 'elderberry']

The key parameter gives you more control over sorting. Instead of comparing the items directly, Python uses a function you provide to generate a value for comparison. In this case, key=len sorts the list of strings based on their length, not their alphabetical order.

  • The len function is applied to each fruit, and the list is rearranged based on those lengths from shortest to longest.
  • That’s why "date" (4 characters) comes first and "elderberry" (10 characters) is last.
  • The key argument is incredibly flexible—you can use any function that takes one argument and returns a value to compare.

Advanced sorting approaches

When your sorting logic needs more nuance than a simple function like len, you can turn to lambda functions, functools.cmp_to_key, and the operator module.

Sorting with lambda functions

people = [("Alice", 25), ("Bob", 19), ("Charlie", 32)]
people.sort(key=lambda x: x[1])
print(people)--OUTPUT--[('Bob', 19), ('Alice', 25), ('Charlie', 32)]

Lambda functions are small, anonymous functions you can define right where you need them. Here, the key is set to lambda x: x[1], which tells Python to sort the list of tuples based on the second element of each tuple—in this case, the age.

  • The function takes each tuple (represented by x) and returns its second item (x[1]) as the sorting key. This arranges the list from youngest to oldest, which is why Bob appears first.

Sorting with functools.cmp_to_key

from functools import cmp_to_key

def compare(a, b):
return a % 10 - b % 10 # Sort by last digit

numbers = [15, 32, 48, 27, 91]
sorted_numbers = sorted(numbers, key=cmp_to_key(compare))
print(sorted_numbers)--OUTPUT--[91, 32, 15, 27, 48]

The functools.cmp_to_key function is a bridge to an older style of sorting. It lets you use a comparison function that takes two arguments, like a and b, and returns a value indicating their relative order. Since modern sorting uses a key, this function adapts that two-argument logic to work with it.

  • The compare function in this example sorts numbers based on their last digit, which it finds using the modulo operator (%).
  • It returns a negative, zero, or positive value to signal the order, and cmp_to_key translates this for the sorted() function.

Sorting with the operator module

import operator

students = [{"name": "Alice", "grade": 85}, {"name": "Bob", "grade": 92}, {"name": "Charlie", "grade": 78}]
sorted_students = sorted(students, key=operator.itemgetter("grade"), reverse=True)
print(sorted_students)--OUTPUT--[{'name': 'Bob', 'grade': 92}, {'name': 'Alice', 'grade': 85}, {'name': 'Charlie', 'grade': 78}]

The operator module offers a clean and efficient alternative to lambda functions for common sorting tasks. Instead of writing a lambda, you can use operator.itemgetter("grade"). This creates a function that retrieves the value for the "grade" key from each student dictionary.

  • The sorted() function then uses these grades as the sorting key.
  • Combined with reverse=True, this arranges the list of students from the highest grade to the lowest. It’s an approach that’s often more readable and can be slightly faster than an equivalent lambda.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

The sorting techniques you've just learned, from simple sort() to custom keys with lambda functions, can be the foundation for powerful tools. Replit Agent can turn these concepts into production-ready applications:

  • Build a leaderboard application that sorts user scores in descending order using reverse=True.
  • Create a task manager that organizes to-do items by priority level or due date, leveraging a custom key.
  • Deploy a product catalog dashboard that allows users to sort items by price, name, or rating with operator.itemgetter.

Describe your app idea, and watch as it gets built, tested, and deployed automatically, all within your browser. Try Replit Agent to turn your concepts into working software faster.

Common errors and challenges

Sorting in Python is usually smooth, but you can hit snags like type mismatches, attribute errors, or missing dictionary keys.

Dealing with TypeError when sorting mixed types

A TypeError pops up when you try to sort a list containing incompatible data types, like numbers and strings. Python can't decide if 5 is greater or less than "apple", so it raises an error to avoid unpredictable results.

To fix this, you can either clean your data to ensure all items are of the same type or use a key function. For example, key=str converts every item to a string before comparison, allowing the sort to proceed without errors.

Handling the AttributeError with immutable sequences

You'll encounter an AttributeError if you try to use the sort() method on an immutable sequence, such as a tuple. Because tuples cannot be changed after they're created, the in-place sort() operation isn't allowed.

The solution is to use the sorted() function instead. It works on any iterable, including tuples, and returns a new, sorted list while leaving the original tuple intact.

Handling dictionaries with missing key values

When sorting a list of dictionaries by a specific key, you might get a KeyError if one of the dictionaries doesn't have that key. This crashes the sort because Python doesn't know what value to use for the comparison.

A robust way to handle this is to use the dictionary's .get() method within your key function. For instance, key=lambda item: item.get('priority', 0) tells Python to use the 'priority' value if it exists, or a default value like 0 if it's missing, preventing the error.

Dealing with TypeError when sorting mixed types

A TypeError occurs when you try sorting a list with incompatible data types, like numbers and strings. Python doesn't know how to compare them, so it raises an error. The code below shows what happens when you call sort() on a mixed list.

mixed_list = [5, "apple", 10, "banana", 2]
mixed_list.sort()
print(mixed_list)

Calling sort() on mixed_list causes a TypeError because Python cannot compare an integer with a string. It doesn't know if 5 should come before or after "apple". The code below shows how to handle this.

mixed_list = [5, "apple", 10, "banana", 2]
numbers = sorted([x for x in mixed_list if isinstance(x, int)])
strings = sorted([x for x in mixed_list if isinstance(x, str)])
result = numbers + strings
print(result)

This solution avoids the error by first separating the data. It uses list comprehensions with isinstance() to create two new lists—one for numbers and one for strings. Each list is then sorted individually using the sorted() function.

Finally, the two sorted lists are concatenated. This method is effective when you need to maintain type integrity and group sorted items separately, which is common when cleaning data from external sources or user input.

Handling the AttributeError with immutable sequences

An AttributeError occurs when you try to call a method that doesn't exist on an object. Since tuples are immutable—meaning they can't be changed—they don't have a sort() method. The code below shows what happens when you try it.

data_tuple = (5, 2, 8, 1, 9)
data_tuple.sort()
print(data_tuple)

This code triggers an AttributeError because it tries to use the in-place sort() method on data_tuple. Tuples are immutable and cannot be modified directly. Check out the code below for the proper way to sort it.

data_tuple = (5, 2, 8, 1, 9)
sorted_data = sorted(data_tuple)
print(sorted_data)
sorted_tuple = tuple(sorted(data_tuple))
print(sorted_tuple)

The fix is to use the sorted() function, which works on any iterable, including tuples. It returns a new sorted list without changing the original data_tuple. This is why it's the go-to for immutable data types. If you need the result to be a tuple, you can simply convert the new list back by wrapping it with the tuple() constructor. This approach gives you a sorted version while respecting the tuple's immutability.

Handling dictionaries with missing key values

When you sort a list of dictionaries using a specific key, you'll run into a KeyError if that key is missing from any dictionary. Python can't find the value to compare, so the operation fails. The code below shows what happens.

students = [
{"name": "Alice", "grade": 85},
{"name": "Bob"}, # Missing "grade" key
{"name": "Charlie", "grade": 78}
]
students.sort(key=lambda x: x["grade"])
print(students)

The lambda function lambda x: x["grade"] fails when it can't find the "grade" key in Bob's dictionary, triggering a KeyError. Check out the code below for a way to handle this gracefully.

students = [
{"name": "Alice", "grade": 85},
{"name": "Bob"}, # Missing "grade" key
{"name": "Charlie", "grade": 78}
]
students.sort(key=lambda x: x.get("grade", 0))
print(students)

The solution uses the dictionary’s .get() method inside the lambda function. Instead of crashing, x.get("grade", 0) provides a default value of 0 whenever the "grade" key is missing. This lets the sort continue without a KeyError.

It's a robust way to handle data from APIs or user inputs, where you can't always guarantee every dictionary will have the same structure.

Real-world applications

With a firm grasp on sorting and error handling, you can apply these techniques to build practical tools like file organizers and leaderboards.

Sorting files by modification date with os.path.getmtime()

You can easily organize files by their last modification date by using the os.path.getmtime() function as a custom sorting key.

import os
from datetime import datetime

files = os.listdir('.')
files.sort(key=lambda x: os.path.getmtime(x))
for file in files[:3]: # Print first 3 files (oldest)
mod_time = datetime.fromtimestamp(os.path.getmtime(file))
print(f"{file}: {mod_time.strftime('%Y-%m-%d %H:%M:%S')}")

This script organizes files in the current directory by their last modification time. It uses os.listdir('.') to get a list of filenames and then sorts them in-place. The key parameter is set to a lambda function that calls os.path.getmtime(), which arranges the files from oldest to newest based on their timestamps.

  • The code then loops through the first three files—the oldest ones in the directory.
  • For each file, it converts the timestamp into a readable format and prints the name alongside its modification date.

Creating a leaderboard with multiple sorted() criteria

By returning a tuple from your key function, you can sort by a primary value and use a secondary value to break ties.

players = [
{"name": "Alice", "score": 192, "time": 45.2},
{"name": "Bob", "score": 192, "time": 39.8},
{"name": "Charlie", "score": 156, "time": 42.1},
{"name": "Diana", "score": 218, "time": 38.6}
]

# Sort by score (descending) and time (ascending) for ties
leaderboard = sorted(players, key=lambda x: (-x["score"], x["time"]))
for rank, player in enumerate(leaderboard, 1):
print(f"{rank}. {player['name']}: {player['score']} pts ({player['time']}s)")

This script builds a leaderboard by sorting players with multiple rules. The magic happens in the key, which uses a lambda function to create a sorting tuple: (-x["score"], x["time"]).

  • Putting a negative sign on x["score"] cleverly reverses the sort order, placing higher scores first.
  • If scores are tied, Python automatically moves to the next item in the tuple, x["time"], sorting players by their time in ascending order.

The enumerate() function then adds a numbered rank to each player in the final list.

Get started with Replit

Turn your sorting skills into a real tool. Tell Replit Agent: “Build a file organizer that sorts by modification date” or “Create a leaderboard API that sorts players by score, then time.”

The agent writes the code, tests for errors, and deploys your app automatically. Start building with Replit to bring your ideas to life.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.