How to sort a list alphabetically in Python

Learn how to sort a list alphabetically in Python. Explore different methods, tips, real-world uses, and how to debug common errors.

How to sort a list alphabetically in Python
Published on: 
Fri
Feb 13, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

Sorting a list alphabetically in Python is a common task for organizing data. Python’s built-in sort() and sorted() functions offer simple, efficient ways to arrange text-based information.

In this article, we'll cover several techniques, from basic methods to advanced tips for complex data. You'll also find real-world applications and debugging advice to help you handle any sorting challenge.

Using the sort() method

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

The sort() method modifies the list it's called on directly. This is known as an in-place operation. Here’s what that means for the fruits list:

  • It doesn't return a new list. The method's return value is None.
  • The original list is permanently altered.

This approach is memory-efficient, especially for large lists, as it avoids creating a copy. The strings are sorted alphabetically by default.

Basic sorting techniques

If modifying the original list with sort() isn't what you need, you can also create a sorted copy, sort case-insensitively, or reverse the order.

Preserving the original list with sorted()

fruits = ["apple", "banana", "cherry", "date", "blueberry"]
sorted_fruits = sorted(fruits)
print(sorted_fruits)
print(fruits) # Original list remains unchanged--OUTPUT--['apple', 'banana', 'blueberry', 'cherry', 'date']
['apple', 'banana', 'cherry', 'date', 'blueberry']

Unlike the sort() method, the built-in sorted() function returns a new, sorted list while leaving the original one unchanged. This is useful when you need to work with a sorted version but also have to preserve the initial order for other operations.

  • The function creates a new list—in this case, sorted_fruits.
  • Your original list, fruits, remains exactly as it was.

Case-insensitive sorting with key=str.lower

mixed_case = ["Apple", "banana", "Cherry", "date", "Blueberry"]
sorted_case_insensitive = sorted(mixed_case, key=str.lower)
print(sorted_case_insensitive)--OUTPUT--['Apple', 'banana', 'Blueberry', 'Cherry', 'date']

Standard sorting is case-sensitive, meaning uppercase letters are grouped before lowercase ones. This is why "Apple" would normally come before "banana". To achieve a true alphabetical sort, you can use the key parameter.

  • Passing key=str.lower tells the function to compare the lowercase versions of the strings.
  • This doesn't change the actual items; the original capitalization is kept in the output list.

Reversing the sort order

fruits = ["apple", "banana", "cherry", "date", "blueberry"]
fruits.sort(reverse=True)
print(fruits)--OUTPUT--['date', 'cherry', 'blueberry', 'banana', 'apple']

For a descending or reverse alphabetical sort, simply add the reverse=True parameter. This argument flips the default A-to-Z order, arranging the list from Z to A. This works with both the in-place sort() method and the sorted() function, giving you flexibility.

  • When you use fruits.sort(reverse=True), the original list is directly modified to reflect the new, reversed order.

Advanced sorting approaches

The key parameter unlocks advanced sorting, letting you organize items by length, custom object attributes, or other complex logic beyond simple alphabetical order.

Sorting by string length

words = ["apple", "banana", "cherry", "date", "blueberry"]
sorted_by_length = sorted(words, key=len)
print(sorted_by_length)--OUTPUT--['date', 'apple', 'banana', 'cherry', 'blueberry']

You can sort a list by the length of its strings by passing the built-in len function to the key parameter. The sorted() function then calls len() on each item and uses the returned integer—the string's length—for comparison instead of the string's alphabetical value.

  • This arranges the list from the shortest string to the longest.
  • If two strings have the same length, their original order is maintained because Python's sort is stable.

Sorting custom objects

class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color
def __repr__(self):
return f"{self.name}({self.color})"

fruits = [Fruit("apple", "red"), Fruit("banana", "yellow"), Fruit("blueberry", "blue")]
sorted_fruits = sorted(fruits, key=lambda fruit: fruit.name)
print(sorted_fruits)--OUTPUT--[apple(red), banana(yellow), blueberry(blue)]

When sorting a list of custom objects, you need to tell Python which attribute to use for comparison. This is where the key parameter shines, often paired with a lambda function—a simple, one-line function for defining the sort logic.

  • The expression key=lambda fruit: fruit.name instructs sorted() to use the name attribute of each object for the comparison.
  • This results in a new list sorted alphabetically by the fruit's name, while leaving the original objects intact. You could just as easily sort by another attribute, like color.

Sorting nested lists

nested_list = [["banana", 3], ["apple", 1], ["cherry", 2]]
sorted_by_first_element = sorted(nested_list, key=lambda x: x[0])
print(sorted_by_first_element)--OUTPUT--[['apple', 1], ['banana', 3], ['cherry', 2]]

Sorting nested lists follows the same logic. You just need to tell the sorted() function which element within each inner list to use for comparison. A lambda function is perfect for this.

  • The key lambda x: x[0] tells Python to look only at the first element (at index 0) of each sublist for sorting.
  • This rearranges the main list based on the alphabetical order of those first elements, leaving the inner lists themselves unchanged.

Move faster with Replit

Replit is an AI-powered development platform where you can start coding Python instantly. It comes with all dependencies pre-installed, so you can skip the setup and environment configuration.

Learning individual techniques is one thing, but building a full application is another. With Agent 4, you can move from piecing together functions to creating complete apps. Instead of just writing code, you describe the product you want to build, such as:

  • A leaderboard tool that sorts players from a nested list based on their score.
  • A content optimizer that organizes a list of headlines by string length to find the most effective options.
  • A product catalog manager that sorts items alphabetically by name, color, or any other attribute.

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 simple tools like sort() and sorted(), you might run into a few common pitfalls when organizing your lists.

Troubleshooting mixed data type sorting

One of the most frequent issues is a TypeError, which happens when you try to sort a list containing different data types, like strings and numbers. Python doesn't know how to compare "apple" to 5, so it stops and raises an error.

To fix this, you can either make sure your list contains only one data type or use the key parameter to convert all items to a single type for comparison. For instance, you could use key=str to treat every item as a string during the sort.

Forgetting that .sort() returns None

It's a classic mistake to assign the result of the sort() method to a new variable. Since sort() modifies the list in-place, it doesn't return a new list—it returns None.

  • If you write sorted_list = my_list.sort(), your sorted_list variable will end up holding None.
  • This often leads to confusing errors later when you try to use what you think is a sorted list.
  • Remember to call my_list.sort() on its own line and then continue using my_list, which is now sorted.

Handling None values in lists

Similar to mixed data types, having None values in a list you want to sort will also cause a TypeError. Python can't compare a string or number to None by default.

The best way to handle this is with a custom key. A clever trick is to use a lambda function that returns a tuple, like key=lambda x: (x is None, x). This sorts all the valid items first and groups all the None values at the end of the list, avoiding the error entirely.

Troubleshooting mixed data type sorting

Python's sorting functions require items of a comparable type. When you mix incompatible types, like strings and integers, Python can't determine their order. This conflict results in a TypeError, as the following code demonstrates when trying to sort the list.

mixed_list = [1, "apple", 3.14, "banana", 2]
mixed_list.sort()
print(mixed_list) # This will raise TypeError

The sort() method tries to compare items like 1 and "apple". Since there's no default way to decide if a number is "greater" than a string, Python raises a TypeError. The following example shows how to resolve this.

mixed_list = [1, "apple", 3.14, "banana", 2]
# Convert all items to strings before sorting
sorted_list = sorted(mixed_list, key=str)
print(sorted_list)

To fix the TypeError, you can use the key=str parameter within the sorted() function. This approach temporarily converts each item to its string representation for comparison, allowing Python to sort the list without errors. For example, the number 1 is compared as the string "1".

  • This is a reliable fix when working with data from external sources, like files or APIs, where types can often be mixed.

Forgetting that .sort() returns None

It's easy to forget that the sort() method doesn't return a new list. It modifies the original one directly and returns None. If you assign its result to a variable, you'll end up with nothing. The code below shows this classic error.

numbers = [5, 2, 8, 1, 9]
sorted_numbers = numbers.sort()
print(sorted_numbers) # Will print None

The error occurs because sorted_numbers captures the return value of .sort(), which is always None. This leaves your new variable empty and can cause unexpected issues later. The correct approach is shown below.

numbers = [5, 2, 8, 1, 9]
numbers.sort() # Sort in-place
print(numbers) # Print the sorted list

The correct approach is to call sort() directly on the list. Since it's an in-place operation, the method alters the list itself and doesn't need to be assigned to a new variable. This is the fix whenever you need to sort a list without creating a copy.

  • Call numbers.sort() on its own line.
  • Use the same variable, numbers, which is now sorted.

Handling None values in lists

Just like with mixed data types, None values will trip up Python's sorting functions. Since None can't be compared to a string or number using operators like <, Python doesn't know how to place it and raises a TypeError. The following code demonstrates this common error.

data = ["apple", None, "banana", None, "cherry"]
data.sort()
print(data) # TypeError: '<' not supported between 'NoneType' and 'str'

The sort() method attempts to compare each item, but it has no built-in logic for ordering a string against a None value. This conflict is what triggers the TypeError. The code below shows how to fix this.

data = ["apple", None, "banana", None, "cherry"]
# Filter out None values before sorting
sorted_data = sorted([item for item in data if item is not None])
print(sorted_data)

A straightforward fix is to filter out the None values before sorting. The example uses a list comprehension to build a new list that excludes any None items. Then, sorted() is called on this clean list, which successfully sorts the remaining strings and avoids a TypeError.

  • Keep an eye out for this when handling data from APIs or databases, as missing values are often represented as None.

Real-world applications

Now that you can navigate common sorting errors, you can apply these techniques to real-world challenges like log analysis and data processing.

Sorting log entries by timestamp

When working with log files, you'll often need to sort entries chronologically, which you can do by targeting the timestamp in each entry.

log_entries = [
{"timestamp": "2023-05-15", "event": "Server restart"},
{"timestamp": "2023-05-10", "event": "Database backup"},
{"timestamp": "2023-05-20", "event": "Security update"}
]
sorted_logs = sorted(log_entries, key=lambda entry: entry["timestamp"])
for log in sorted_logs:
print(f"{log['timestamp']}: {log['event']}")

This example organizes a list of log entries, where each entry is a dictionary. The sorting logic is handled by the key parameter within the sorted() function, which is ideal for complex data structures like this.

  • A lambda function, lambda entry: entry["timestamp"], tells Python exactly what to compare.
  • For each dictionary in the list, it extracts the value associated with the "timestamp" key.
  • Because the date strings are in a standard format, sorting them alphabetically also arranges them chronologically from earliest to latest.

Multi-criteria sorting for data analysis with sorted()

For more advanced tasks, you can sort by multiple criteria at once, such as ordering a list of employees by department and then by salary in descending order.

employees = [
{"name": "Alice", "department": "Engineering", "salary": 85000},
{"name": "Bob", "department": "Marketing", "salary": 75000},
{"name": "Charlie", "department": "Engineering", "salary": 90000},
{"name": "Diana", "department": "Marketing", "salary": 80000}
]
# Sort by department (primary) and then by salary (secondary, descending)
sorted_employees = sorted(employees, key=lambda e: (e["department"], -e["salary"]))
for emp in sorted_employees:
print(f"{emp['name']} - {emp['department']}: ${emp['salary']}")

This snippet showcases multi-level sorting by passing a tuple to the key parameter. Python uses the elements of the tuple in order to resolve sorting ties.

  • First, it sorts the list based on the department name, e["department"].
  • When departments are the same, it uses the second key, -e["salary"], to break the tie. The negative sign is a clever trick that inverts the numerical sort, placing higher salaries before lower ones. This achieves a descending order for the secondary criterion.

Get started with Replit

Now, turn your knowledge into a working tool. Describe what you want to build to Replit Agent, like "a contact manager that sorts names" or "a script that alphabetizes words from a file".

Replit Agent writes the code, tests for errors, and helps you deploy the app. Start building with Replit.

Build your first app today

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.

Build your first app today

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.