How to sort a list alphabetically in Python

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

How to sort a list alphabetically in Python
Published on: 
Fri
Feb 13, 2026
Updated on: 
Tue
Feb 24, 2026
The Replit Team Logo Image
The Replit Team

Sorting a list alphabetically in Python is a fundamental skill. The language offers powerful built-in functions that make organizing textual data straightforward, requiring only a few lines of code.

In this article, you'll explore techniques for alphabetical sorting. You'll find practical tips, see real-world applications, and get debugging advice to help you confidently handle any sorting task.

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. Notice how you don't assign the result back to the fruits variable; the original list is altered permanently.

  • Efficiency: It's memory-efficient because it doesn't create a new list.
  • Return Value: The method returns None, a common source of bugs if you try to assign its result, for example, new_list = fruits.sort().

Basic sorting techniques

Beyond the in-place sort() method, you can also sort lists while preserving the original, ignoring case, or even reversing the alphabetical 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']

The sorted() function offers a non-destructive alternative. It works by taking an iterable, like your fruits list, and returning a brand new sorted list. This approach is ideal when you need to preserve the original list's order for later use.

  • Return Value: Unlike the sort() method, it returns a new list that you can assign to a variable.
  • Original Data: Your original list remains completely unchanged, which prevents unintended side effects in your code.

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']

Python's default sort is case-sensitive, which means it places all uppercase letters before lowercase ones. To get a true alphabetical sort, you can use the key parameter to tell the function how to evaluate each item for comparison.

  • Setting key=str.lower instructs the sorted() function to compare the lowercase version of each string.
  • This comparison doesn't change the items themselves. The final list preserves the original capitalization, giving you a properly alphabetized result while keeping the original casing intact.

Reversing the sort order

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

To flip the sort order, you can use the reverse parameter. Setting reverse=True tells the function to arrange the list in descending alphabetical order—from Z to A—instead of the default ascending order.

  • This boolean flag works with both the in-place sort() method and the sorted() function, giving you consistent control whether you modify the list or create a new one.

Advanced sorting approaches

Beyond the basics, the key parameter unlocks advanced sorting capabilities, allowing you to organize lists based on string length, custom objects, and even nested structures.

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']

The key parameter is incredibly versatile. By setting key=len, you instruct the sorted() function to organize the list based on the length of each string, from shortest to longest. You're passing the built-in len function itself as an argument, which Python then applies to every item to determine its sort value.

  • When items have the same length, like "banana" and "cherry", their original relative order is preserved. This is 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)]

Sorting lists of custom objects requires telling Python which attribute to compare. The key parameter is perfect for this, especially when paired with a lambda function. A lambda is a small, anonymous function that defines sorting logic on the fly.

  • In this example, key=lambda fruit: fruit.name tells sorted() to extract the name from each Fruit object.
  • The function then uses these names to alphabetize the list, returning a new list of objects in the correct order.

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 is straightforward when you use a lambda function to target a specific element for comparison. This approach lets you define sorting logic based on any value within the nested structure.

  • With key=lambda x: x[0], you're telling the function to look only at the first item (at index 0) of each inner list.
  • The sort operation then alphabetizes the outer list based on those targeted strings, moving the entire inner lists to their new, sorted positions.

Move faster with Replit

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

The sorting techniques from this article, from a simple sort() to advanced keys, can be the foundation for powerful tools. Replit Agent can turn these concepts into production applications.

  • Build a contact management tool that sorts user lists alphabetically, ignoring case with key=str.lower.
  • Create a playlist generator that organizes songs by artist name from a list of custom track objects.
  • Deploy a data visualization dashboard that sorts inventory items by name from a nested list of product data.

Turn your idea into a working application by describing it to Replit Agent. It writes the code, tests it, and handles issues automatically, all within your browser.

Common errors and challenges

While Python's sorting tools are powerful, a few common pitfalls can trip you up, especially when your data isn't perfectly uniform.

Troubleshooting mixed data type sorting

Python's sorting functions will raise a TypeError if you try to sort a list containing incompatible data types, like strings and numbers. The interpreter doesn't know how to compare "apple" to 5, so it stops.

To resolve this, you can either preprocess the list to ensure all items are of the same type—for example, by converting everything to strings with str()—or use a more advanced key function to define custom comparison logic.

Forgetting that .sort() returns None

A classic mistake is assigning the output of the sort() method back to a variable, as in my_list = my_list.sort(). Because the method modifies the list in-place, it returns None. This action overwrites your variable, and you'll effectively lose your data.

Remember to call sort() on its own line to modify the list directly. If you need to keep the original and create a new sorted version, the sorted() function is the right tool for the job.

Handling None values in lists

Just like with mixed data types, attempting to sort a list that includes None values alongside other types will also trigger a TypeError. Python can't compare a string or number to None by default.

  • Your simplest option is to filter out all None values from the list before you perform the sort.
  • Alternatively, you can use the key parameter with a lambda function to handle None. This lets you define a fallback value for comparison, such as an empty string, allowing the sort to complete without errors.

Troubleshooting mixed data type sorting

Python's sorting functions expect items of a similar type. When you mix incompatible types, like numbers and strings, the interpreter can't decide which comes first. This ambiguity causes the operation to fail, raising a TypeError. The following code demonstrates this issue.

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

The sort() method fails because it can't directly compare numbers and strings, like 1 and "apple". To fix this, you need to tell Python how to handle these different types. Check out the following example for a solution.

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)

The fix works by passing key=str to the sorted() function. This temporarily converts each item—like the number 1—into its string equivalent ("1") for comparison, which resolves the TypeError. The original items in the list keep their types. You'll find this approach especially helpful when sorting data from sources like APIs or files, where you can't always guarantee uniform data types.

Forgetting that .sort() returns None

It's a classic slip-up: you call the sort() method and assign its result to a new variable. Since sort() modifies the list directly—an in-place operation—it returns None, and you accidentally erase your list. The code below shows this common pitfall in action.

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

The assignment sorted_numbers = numbers.sort() captures the method's return value, which is None. Because sort() modifies the list in-place, this action overwrites your data. The example below shows how to avoid this common error.

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

The fix is to call numbers.sort() without assigning its result to a variable. Since the method operates in-place, it directly rearranges the items within the numbers list itself. After the call, the numbers variable holds the sorted sequence. This is the key difference from functions that return a new, modified copy; sort() changes the original data structure.

Handling None values in lists

When your list contains None values mixed with other data types, Python's sorting functions will raise a TypeError. The interpreter can't compare an object like a string to None, as there's no default order between something and nothing.

The following code illustrates this common error, which you'll often encounter when working with incomplete datasets.

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

The sort() method can't decide where to place None in relation to a string like "apple", causing the operation to fail. The code below shows how to give the function a clear rule to follow.

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)

The most direct fix is to filter out the None values. The solution uses a list comprehension, [item for item in data if item is not None], to build a new list that excludes any None entries. The sorted() function can then alphabetize this clean list without raising an error. You'll find this is a common step when handling data from databases or APIs, where fields can often be empty or missing.

Real-world applications

With a solid grasp of sorting and troubleshooting, you can apply these skills to practical challenges like organizing log entries and analyzing complex data.

Sorting log entries by timestamp

To make sense of application behavior or system events, you can sort log entries chronologically by targeting each entry's timestamp.

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 shows how to sort a list where each item is a dictionary. Since Python can't compare dictionaries directly, you must tell the sorted() function which value inside each dictionary to use for the comparison. This is done with the key parameter.

  • A lambda function, lambda entry: entry["timestamp"], provides the sorting logic on the fly.
  • For each dictionary in the list, it extracts the value associated with the "timestamp" key.
  • The sorted() function then uses these extracted string values to arrange the dictionaries, returning a new, properly ordered list.

Multi-criteria sorting for data analysis with sorted()

For more complex data analysis, you can sort by multiple criteria at once by having the key function return a tuple of values.

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 code sorts the list of employees using two rules, which are defined by the lambda function passed to the key parameter.

  • First, it organizes the list alphabetically by the value of the department key.
  • If employees share the same department, it then uses a secondary rule, sorting them by salary. Using a negative sign, as in -e["salary"], is a common trick to reverse the numerical sort order, arranging salaries from highest to lowest.

Get started with Replit

Turn your sorting skills into a real application. Describe what you want to build, like "a tool to alphabetize a contact list by last name" or "an app that sorts a product inventory by name."

Replit Agent writes the code, tests for errors, and deploys your app right from your browser. Start building with Replit.

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.