← Back to Articles
Tutorial

How to Sort a List in Python Easily

Learn how to sort lists in Python efficiently with examples, best practices, and common pitfalls to avoid.

Sorting a list is a common task in programming, and Python provides several ways to achieve this. Whether you need to sort numbers, strings, or custom objects, Python's built-in functions make it easy and efficient.

The simplest way to sort a list in Python is by using the built-in `sorted()` function, which returns a new list. Alternatively, the `list.sort()` method sorts the list in place. For example, `sorted_list = sorted(my_list)` or `my_list.sort()`. You can also specify sorting criteria using the `key` parameter.

For best practices, use `sorted()` when you need a new list and `list.sort()` when you want to modify the original list. Consider using the `key` parameter to sort complex objects or to sort based on custom criteria.

Avoid common mistakes like trying to sort lists containing incompatible types without a key function. Also, remember that `list.sort()` modifies the list in place and does not return a new list, which is a frequent source of confusion.

Code Examples

Example 1

my_list = [3, 1, 4, 1, 5, 9]
sorted_list = sorted(my_list)
print(sorted_list)  # Output: [1, 1, 3, 4, 5, 9]

Example 2

my_list = ['banana', 'apple', 'cherry']
my_list.sort()
print(my_list)  # Output: ['apple', 'banana', 'cherry']

More Python Tutorials