Python

Python

Python - Sorting Lists

Python provides powerful and convenient tools for sorting lists.

What is Sorting?

Sorting is the process of arranging elements in a list according to a specific criterion, such as ascending or descending order. In Python, lists can contain numbers, strings, or even more complex objects, each with its own peculiarities.

Example of an unsorted list:

numbers = [5, 2, 8, 1, 9, 3]

After sorting in ascending order, it becomes:

numbers = [1, 2, 3, 5, 8, 9]

Python offers two main ways to sort lists:

  1. The .sort() method — modifies the original list "in place."
  2. The sorted() function — returns a new sorted list without altering the original.

Let’s dive into both approaches step by step.

The .sort() Method — In-Place Sorting

The .sort() method belongs to the list object and modifies it directly. This is handy when you don’t need to preserve the original order of elements.

📌 Example

Here, the numbers list is sorted in ascending order. Note: the .sort() method doesn’t return anything (it returns None); it simply modifies the list.

Sorting in Descending Order

To sort a list in descending order, use the reverse=True parameter:

Sorting Strings

The .sort() method also works with lists of strings. By default, strings are sorted lexicographically (like in a dictionary):

Python compares strings character by character based on their Unicode code points. For example, "apple" comes first because "a" is less than "b," "o," or "p."

You can check a character’s code point using the built-in ord() function:

Sorting strings with conversion to numbers:

Features of .sort()

  • Works only with lists. Attempting to call .sort() on a tuple or set will raise an error.
  • All elements in the list must be comparable with each other. For instance, you can’t sort [1, "two", 3] because numbers and strings can’t be compared directly.

Example of an error:

The sorted() Function — Creating a New Sorted List

The sorted() function is more versatile: it works with any iterable (lists, tuples, sets) and returns a new sorted list without modifying the original.

📌 Example

Sorting in Descending Order

Like .sort(), the sorted() function has a reverse parameter:

Working with Other Data Types

The sorted() function can sort not just lists but also tuples or sets, for example:

Advantages of sorted()

  • Doesn’t modify the original object, which is useful if you need to keep the original data intact.
  • Works with any iterable, not just lists.

Custom Sorting with the key Parameter

Both .sort() and sorted() allow you to specify a custom sorting criterion using the key parameter. This parameter takes a function that defines how elements should be compared.

Sorting by String Length

Suppose you want to sort a list of words by their length:

Here, the len function returns the length of each string, and the list is sorted in ascending order by length: "kiwi" (4 characters), "pear" (4 characters), "apple" (5 characters), "banana" (6 characters).

For descending order, add reverse=True:

Sorting by the Last Letter

To sort words by their last letter, you can define a custom function:

  • word[-1] returns the last letter of the word.
  • The list is sorted by those letters: "a" (banana), "e" (apple), "i" (kiwi), "r" (pear).

The same with sorted():

Sorting Numbers by Remainder

Example of sorting numbers by their remainder when divided by 3:

  • lambda x: x % 3 is an anonymous function that returns the remainder of a number divided by 3.
  • Numbers are sorted by remainders: 0 (3, 9), 1 (1, 4, 7), 2 (11).

Sorting Complex Structures

If a list contains lists, tuples, or dictionaries, you can sort them by a specific element.

Sorting a List of Tuples

Suppose you have a list of tuples where the first element is a name and the second is an age:

To sort by age (the second element):

Sorting a List of Dictionaries

Example of sorting a list of dictionaries by the "age" key:

Which to Choose: sort() or sorted()?

Both tools are designed for sorting lists, but they differ in behavior and use cases.

.sort() Method sorted() Function
What it does? Sorts the list "in place," modifying the original list directly. Creates a new sorted list, leaving the original unchanged.
Return value Nothing (None) A new list
Applicability Only works with lists Works with any iterable (lists, tuples, sets, dictionaries, etc.)
When to use? When you don’t need the original order and want to modify the list for further use. When you want to preserve the original order and use the sorted version separately.
Memory usage Uses less memory since it doesn’t create a new list, which can matter with large data. Requires extra memory for the copy, which can be noticeable with very large lists.

If in doubt, start with sorted() — it’s safer for your data and more flexible.

The reverse() Method: Reversing, Not Sorting

Beginners often confuse the .reverse() method with sorting in descending order using sort(reverse=True). Let’s clarify the difference.

The .reverse() method doesn’t sort the list; it simply reverses its order, swapping elements without considering their values. It’s like flipping a stack of cards upside down.

📌 Example

Here, the list is simply "mirrored": the first element becomes the last, the second becomes the second-to-last, and so on.

Comparison with sorting:

Key difference:

  • Sorting (sort() or sorted()) arranges elements according to a rule (e.g., ascending order).
  • Reversing (reverse()) changes the order without any sorting logic, just flipping the list.

Features of .reverse():

  • Works only with lists (like .sort()).
  • Modifies the list in place and returns None.
  • Takes no parameters, unlike .sort() or sorted().

Useful Tips and Pitfalls

  1. Element Comparability: Ensure all list elements can be compared with each other.
  2. String Case Sensitivity: Python considers case when sorting strings ("A" < "a"). To ignore case:
  1. Sorting Stability: Python uses a stable sorting algorithm called Timsort. This means that if two elements are equal according to the sorting criterion, their original order is preserved.

This wonderful property allows you to perform complex sorts with multiple steps. For example, to sort students by descending grade and then by ascending age, first sort by age, then by grade.

The Timsort algorithm efficiently handles multiple sorts by leveraging any existing order in the data.

Advanced Techniques

Getting the Top 5 Elements

In Python, you can get the top 5 elements of a list without sorting the entire list. The heapq module from the standard library, which implements a heap data structure, is perfect for this.

The heapq.nlargest() method efficiently finds the n largest elements without fully sorting the list. This is especially useful for large lists where full sorting might be overkill and time-consuming.

📌 Example Using heapq.nlargest()

  • nlargest(5, numbers) returns the 5 largest elements in descending order.
  • The original numbers list remains unchanged.

heapq.nlargest() uses a heap-based algorithm that’s faster than full sorting. Its time complexity is O(n log k), where n is the list length and k is the number of elements to find (here, 5). This beats O(n log n) for a full sort followed by slicing.

For comparison, sorting the entire list with sorted() and taking the first 5 elements is slower for large datasets:

📌 Example: Getting the Bottom 5 Elements

To find the smallest elements, use heapq.nsmallest():

Like sort() or sorted(), you can use the key parameter for custom logic. For example, finding the top 3 strings by length:

For small lists, the speed difference is negligible, and sorted() with slicing works fine. But for lists with thousands or millions of elements, when you only need the top 5, full sorting is unnecessary work. heapq.nlargest() saves time and resources.

How to Sort a List with Mixed Data Types?

You can’t directly sort a list with incomparable data types, as Python will raise a TypeError.

There are several ways to handle this.

The safest approach is to sort using a key that converts all elements to a single type or returns a tuple with type information:

You can create a more complex key that considers both type and value:

For a specific type order:

Sometimes it’s better to separate the list by type, sort each group individually, and then combine them:

The approach depends on your specific sorting requirements and the types of data in your list.

Auto-Sorting

A regular Python list doesn’t support automatic sorting. If you add elements and want to maintain order, you have to call .sort() or sorted() each time, which can be slow for large data: O(n log n) per sort. The SortedList class from the sortedcontainers module solves this by automatically maintaining order when adding or removing elements, with a lower complexity of O(log n) for insertions.

The sortedcontainers module is a third-party library that provides data structures with automatic sorting support. Unlike Python’s built-in types like lists or sets, SortedList, SortedDict, and SortedSet keep elements sorted at all times.

Key features of SortedList:

  • Automatic sorting — elements are always ordered.
  • Fast operations — adding, removing, and searching are efficient.
  • Indexing — access elements by index, like a regular list.
  • Flexibility — supports custom sorting keys.

Let’s look at some examples to see how it works.

First, install the library via pip:

pip install sortedcontainers

📌 Example 1: Creating a List and Adding Elements

📌 Example 2

We imported SortedList and created an empty list. Then we added numbers using the .add() method. Notice how the elements are automatically sorted in ascending order, even though we added them in random order.

📌 Example 3: Custom Sorting

The key argument lets you specify a function for sorting. Here, we sort strings by length. When a new element is added, it automatically takes its proper position.

When to use SortedList?

  • When you need a list that’s always sorted.
  • When you frequently add or remove elements and want to avoid manual sorting.
  • For tasks where performance matters with ordered data (e.g., finding the nearest value or maintaining a top-N list).

Conclusion

Sorting lists in Python is a simple yet powerful tool. The .sort() method is great for modifying a list in place, while sorted() offers flexibility and preserves the original data. With the key parameter, you can tailor sorting to any need, from simple numbers and strings to complex objects.

Try experimenting with the examples above, tweaking the data and sorting criteria. It’s the best way to solidify your understanding of how sorting works in Python.

Frequently Asked Questions About Sorting Lists in Python

How do I sort a list in Python in ascending order?

To sort a list in ascending order, use the built-in .sort() method or the sorted() function. The .sort() method modifies the original list, while sorted() returns a new sorted list without changing the original.

How do I sort a list in Python in descending order?

To sort a list in descending order, use the reverse=True parameter with either .sort() or sorted().

How do I sort a list by multiple criteria?

To sort by multiple criteria, use tuples as the sorting key.

Subscribe to our newsletter

Get the freshest news and resources for developers, designers and digital creators in your inbox each week

© 2000 – 2025 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.