How to sort an array in Python
Learn how to sort an array in Python. Discover different methods, tips, real-world applications, and how to debug common sorting errors.

To sort an array in Python is a fundamental skill for data manipulation and algorithm design. Python provides powerful built-in functions to make this process simple and efficient.
Here, you'll explore several sorting techniques, from the simple sort() method to more advanced custom sorts. You'll also find practical tips, real-world applications, and advice to debug common sorting issues.
Using the list.sort() method
numbers = [5, 2, 8, 1, 9]
numbers.sort()
print(numbers)--OUTPUT--[1, 2, 5, 8, 9]
The list.sort() method modifies the list directly, a process known as in-place sorting. This means it doesn't create a new list; instead, it rearranges the elements within the original numbers list itself. By default, the sort is performed in ascending order.
- Efficiency: Because it sorts in-place, it's memory-efficient for large lists since no copy is made.
- Side Effects: The original order of your list is lost. Be mindful of this if you need to preserve the initial state of your data.
Basic sorting techniques
While list.sort() modifies the list directly, Python offers more flexible tools like the sorted() function for creating new sorted lists and customizing the sort order.
Using the sorted() function
numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers)
print("Original:", numbers)
print("Sorted:", sorted_numbers)--OUTPUT--Original: [5, 2, 8, 1, 9]
Sorted: [1, 2, 5, 8, 9]
Unlike the list.sort() method, the sorted() function returns a new, sorted list while leaving the original list untouched. This is a safer choice when you need to preserve your initial data. It's also more versatile.
- Flexibility: You can use
sorted()on any iterable—including tuples, strings, and sets—not just lists. - Non-destructive: Since it creates a new list, you don't have to worry about accidentally modifying your original data.
Sorting in descending order
numbers = [5, 2, 8, 1, 9]
numbers.sort(reverse=True)
print(numbers)--OUTPUT--[9, 8, 5, 2, 1]
To flip the sort order, simply add the reverse=True argument. This parameter tells Python to arrange the elements from largest to smallest instead of the default smallest to largest.
- This works for both the
list.sort()method and thesorted()function. - In the example,
numbers.sort(reverse=True)rearranges the list in-place, just as it does for an ascending sort.
Sorting with a custom key function
words = ["apple", "Banana", "cherry", "Date"]
words.sort(key=str.lower)
print(words)--OUTPUT--['apple', 'Banana', 'cherry', 'Date']
For more complex sorting, the key parameter is your best friend. It lets you specify a function to be called on each list element before making comparisons. This function's return value is then used as the basis for sorting.
- In this example,
key=str.lowertells the sort to treat all words as if they were lowercase. - This results in a case-insensitive sort, where "apple" correctly comes before "Banana". Notice that the original capitalization in the list remains unchanged.
Advanced sorting techniques
For more intricate sorting logic, you can pair the key parameter with lambda functions or use specialized tools like itemgetter and functools.cmp_to_key.
Using lambda for custom sort criteria
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
students.sort(key=lambda student: student[1], reverse=True)
print(students)--OUTPUT--[('Bob', 92), ('Alice', 85), ('Charlie', 78)]
When your sorting logic is simple, a lambda function offers a clean and concise solution. It lets you create a small, anonymous function right where you need it—inside the key argument, without defining a separate function.
- The expression
lambda student: student[1]tells the sort method to use the second element of each tuple (the score) as the sorting key. - By adding
reverse=True, you sort the students from the highest score to the lowest, placing Bob at the top of the list.
Sorting by multiple attributes with itemgetter
from operator import itemgetter
items = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 25}, {"name": "Charlie", "age": 20}]
sorted_items = sorted(items, key=itemgetter("age", "name"))
print(sorted_items)--OUTPUT--[{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 25}]
When you need to sort by multiple fields, itemgetter from the operator module is a clean and efficient tool. It's especially handy for sorting complex data structures like lists of dictionaries. It lets you create a sort key that considers more than one attribute in a specific order.
- The expression
key=itemgetter("age", "name")sets up a two-level sort. Python first sorts the list based on the "age" value. - If two items have the same age, like Alice and Bob, it uses the "name" value as a tiebreaker, sorting them alphabetically.
Complex sorting with functools.cmp_to_key
from functools import cmp_to_key
def version_compare(v1, v2):
v1_parts = list(map(int, v1.split('.')))
v2_parts = list(map(int, v2.split('.')))
return -1 if v1_parts < v2_parts else 1 if v1_parts > v2_parts else 0
versions = ["1.2", "1.10", "1.1", "2.0"]
sorted_versions = sorted(versions, key=cmp_to_key(version_compare))
print(sorted_versions)--OUTPUT--['1.1', '1.2', '1.10', '2.0']
For truly custom sorting logic, cmp_to_key from the functools module provides a powerful bridge. It adapts an old-style comparison function—one that directly compares two items—for use with modern sorting tools that expect a key. This is perfect for complex rules where a simple key isn't enough.
- The custom
version_comparefunction implements the specific logic, returning-1,0, or1to indicate the order of two version strings. - This is essential for cases like software versions, where a simple alphabetical sort would incorrectly place "1.10" before "1.2".
cmp_to_keywraps this comparison logic, allowingsorted()to use it effectively.
Move faster with Replit
Replit is an AI-powered development platform where all Python dependencies pre-installed, so you can skip setup and start coding instantly. It's designed to help you move from learning individual techniques to building complete applications. With Agent 4, you can describe what you want to build, and it handles everything from writing code to deployment.
Instead of piecing together sorting functions, you can use Agent to build a finished product. For example, you could create:
- A high-score tracker for a game that sorts players by score in descending order.
- An inventory management system that organizes products first by category, then alphabetically by name.
- A deployment utility that correctly sorts software version numbers, ensuring "1.10" is handled as newer than "1.2".
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Even with Python's simple tools, you might run into a few common sorting snags that can trip you up.
Trying to sort a tuple with sort()
Since tuples are immutable, they can't be changed after creation. The list.sort() method modifies a list in-place, so it doesn't exist for tuples. If you try to call my_tuple.sort(), you'll get an AttributeError.
- The Fix: Use the
sorted()function instead. It works on any iterable, including tuples, and returns a new sorted list while leaving the original tuple untouched.
Sorting mixed data types
In Python 3, you can't compare elements of different types, like an integer and a string. Attempting to sort a list containing mixed types (e.g., [1, "apple", 5, "banana"]) will raise a TypeError because Python doesn't know how to order a number against a word.
- The Fix: Provide a
keyfunction to convert all elements to a comparable type. For instance, usingkey=strtells the sort function to treat every item as a string for comparison purposes, resolving the error.
Fixing the sort() returns None error
A classic beginner mistake is assigning the result of list.sort() to a variable, like sorted_list = my_list.sort(). This won't work as you expect because the sort() method modifies the list directly and returns None.
- The Fix: If you want to sort the list in-place, just call the method on its own line:
my_list.sort(). If you need to create a new sorted list and assign it to a variable, use thesorted()function:sorted_list = sorted(my_list).
Trying to sort a tuple with sort()
A common mistake is trying to use the sort() method on a tuple. Because tuples are immutable—meaning they can't be changed—this operation isn't allowed. Attempting to do so will result in an AttributeError, as the following code demonstrates.
numbers = (5, 2, 8, 1, 9)
numbers.sort()
print(numbers)
This code triggers an AttributeError because the sort() method is a list-specific tool. You're trying to use it on a tuple, which doesn't support in-place changes. Check out the example below for the proper way to sort it.
numbers = (5, 2, 8, 1, 9)
sorted_numbers = sorted(numbers)
print(sorted_numbers)
The correct approach is using the sorted() function, which is designed to work with any iterable, including immutable tuples. It doesn't try to change the original tuple. Instead, it returns a new, sorted list containing the tuple's elements, which you can then assign to a new variable.
- This is your go-to method whenever you need to sort an immutable sequence or want to preserve the original data while creating a sorted copy.
Sorting mixed data types
Python's sorting functions require elements to be comparable. When you try to sort a list containing mixed data types, like numbers and strings, Python can't determine a logical order. This conflict results in a TypeError, as the code below demonstrates.
mixed_list = [1, "apple", 3, "banana"]
mixed_list.sort()
print(mixed_list)
This code raises a TypeError because Python can't decide if 1 should come before or after "apple". The comparison isn't defined between numbers and strings. Check out the example below for the correct approach.
mixed_list = [1, "apple", 3, "banana"]
sorted_strings = sorted([str(item) for item in mixed_list])
print(sorted_strings)
The fix is to make all elements comparable before sorting. The list comprehension [str(item) for item in mixed_list] creates a new list where every element is converted to a string using str(). The sorted() function can then arrange these strings alphabetically without issue.
- This is a key technique to remember when you're working with data from external sources, like files or user input, where data types can be inconsistent.
Fixing the sort() returns None error
A classic mistake is assigning the result of list.sort() to a variable. Because this method sorts the list in-place and returns None, you'll find your new variable is empty. The code below demonstrates this common but confusing behavior.
numbers = [5, 2, 8, 1, 9]
sorted_numbers = numbers.sort()
print(sorted_numbers)
The code captures the return value of numbers.sort(), which is always None because the method modifies the list directly. As a result, sorted_numbers holds nothing, and that’s what gets printed. See the correct approach below.
numbers = [5, 2, 8, 1, 9]
numbers.sort()
print(numbers)
The fix is simple: call numbers.sort() on its own line without assigning it to a variable. Because the method sorts the list in-place, the original numbers list is permanently changed. You can then use this newly sorted list for whatever you need next.
- Remember this distinction: use
list.sort()for in-place sorting andsorted()when you need to create a new sorted list while preserving the original.
Real-world applications
Now that you understand the mechanics, you can sort logs with datetime.strptime() or score search results with a custom key.
Sorting log entries with datetime.strptime()
To sort text-based log entries chronologically, you'll need to use the datetime.strptime() function to convert the timestamp string in each entry into a proper datetime object for accurate comparison.
from datetime import datetime
log_entries = [
"2023-03-15 14:32:10 INFO Server started",
"2023-03-15 14:35:22 ERROR Connection failed",
"2023-03-15 14:30:05 WARNING Low memory",
"2023-03-15 14:33:18 INFO User logged in"
]
sorted_logs = sorted(log_entries, key=lambda x: datetime.strptime(x[:19], "%Y-%m-%d %H:%M:%S"))
for log in sorted_logs:
print(log)
This code sorts log entries by their timestamps, but not alphabetically. Instead, it uses a custom key to interpret the date and time information correctly.
- The
lambdafunction isolates the timestamp from each log string using the slicex[:19]. datetime.strptime()then parses this string slice, converting it into a properdatetimeobject that Python can compare chronologically.
This transformation is crucial because it allows sorted() to arrange the log entries based on when they actually occurred, not just their text value.
Building a search engine with custom key scoring
A custom key function allows you to build a basic search engine that scores files for relevance, combining factors like keyword frequency and file size.
def compute_relevance(file_info, query):
filename, content, size = file_info
keyword_score = content.lower().count(query.lower()) * 10
size_score = 1000 / (size + 100) # Smaller files get higher scores
return keyword_score + size_score
files = [
("document1.txt", "This is about Python programming", 150),
("document2.txt", "Python basics and advanced Python concepts", 200),
("document3.txt", "Java and C++ programming guide", 180),
("document4.txt", "Quick Python reference", 100)
]
search_query = "python"
sorted_files = sorted(files, key=lambda x: compute_relevance(x, search_query), reverse=True)
for file, content, size in sorted_files:
relevance = compute_relevance((file, content, size), search_query)
print(f"{file} (Relevance: {relevance:.2f})")
This code ranks files based on a custom relevance score for a given search query. The compute_relevance function calculates this score by combining two metrics:
- A keyword score based on how often the
queryappears in the content. - A size score that gives preference to smaller files.
The sorted() function then uses this multi-factor score as its key to arrange the files. Setting reverse=True ensures the most relevant files—those with the highest scores—appear first, demonstrating how a key can implement sophisticated sorting logic.
Get started with Replit
Now, turn these sorting techniques into a real tool. Describe what you want to build, like "a log file analyzer that sorts entries by timestamp" or "a tool to rank sales leads by a custom score."
Replit Agent writes the code, tests for errors, and deploys the app from your description. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



