5 Best Ways to Sort in Python

πŸ’‘ Problem Formulation: Learning how to sort data is a fundamental skill in programming, including in Python. Efficient sorting is critical for tasks such as preparing data for analysis, searching through datasets, or rendering information in a readable format. Let’s consider having a list of integers [4, 1, 3, 2] and needing this list sorted in ascending order to become [1, 2, 3, 4].

Method 1: The sorted() Function

The sorted() function is a built-in Python method that returns a new sorted list from the items in any iterable (like lists, tuples, dictionaries). The function is versatile, offering parameters to customize the sort order and criteria without modifying the original data.

Here’s an example:

numbers = [4, 1, 3, 2]
sorted_numbers = sorted(numbers)

Output:

[1, 2, 3, 4]

This code snippet utilizes the sorted() function to sort a list of integers. Without any extra parameters, sorted() sorts the list in ascending order by default, resulting in a sorted list that is stored in sorted_numbers.

Method 2: The sort() Method

The list.sort() method sorts the elements of a given list in a specific ascending or descending order. This method alters the original list and does not return any value, making it particularly memory efficient for large lists.

Here’s an example:

numbers = [4, 1, 3, 2]
numbers.sort()

Output:

[1, 2, 3, 4]

By calling numbers.sort(), we sort the list in-place. After execution, the original numbers list is sorted, reflecting the change directly in the original list.

Method 3: Using a Lambda Function for Custom Sorts

Custom sorting can be achieved by passing lambda functions as the key argument to sorted() or sort(). This allows fine control over the sort order and criteria based on a function that processes each item.

Here’s an example:

words = ['banana', 'pie', 'apple', 'cherry']
sorted_words = sorted(words, key=lambda x: x[-1])

Output:

['banana', 'apple', 'pie', 'cherry']

This snippet sorts a list of words based on the last letter of each word. The lambda function lambda x: x[-1] is used as the sorting criterion, producing a list sorted by the final character in each word.

Method 4: Sorting with itemgetter()

Using the itemgetter() from the operator module provides an efficient way to sort lists of tuples or objects based on object attributes. This is typically faster than lambda functions for simple attribute access.

Here’s an example:

from operator import itemgetter
pairs = [(2, 'apple'), (1, 'banana'), (4, 'cherry'), (3, 'pie')]
sorted_pairs = sorted(pairs, key=itemgetter(1))

Output:

[(1, 'banana'), (4, 'cherry'), (2, 'apple'), (3, 'pie')]

By using itemgetter(1), the list of tuples is sorted based on the second element of each tuple. The result is that sorted_pairs is ordered alphabetically by the fruit names.

Bonus One-Liner Method 5: Sort by Reverse Order

Sometimes, you may want to sort a list in reverse order, which you can easily achieve by using the reverse=True parameter in either the sorted() function or the list.sort() method.

Here’s an example:

numbers = [4, 1, 3, 2]
sorted_numbers_desc = sorted(numbers, reverse=True)

Output:

[4, 3, 2, 1]

This one-liner sorts the numbers in descending order by setting reverse=True inside the sorted() function call. The outcome is the list sorted from highest to lowest number.

Summary/Discussion

  • Method 1: sorted() Function. Standalone usage. Creates a new sorted list. Does not modify the original data. Can sort any iterable, not just lists.
  • Method 2: sort() Method. In-place modification. Does not create a new list, which can save memory. Only applies to lists.
  • Method 3: Lambda Functions. High customizability. Can sort based on complex criteria. May be slower than other methods for simple tasks.
  • Method 4: itemgetter(). Efficient for simple attribute-based sorting. Faster than lambdas for certain operations. Requires importing an extra module.
  • Bonus Method 5: Reverse Order. Quick and easy to sort in reverse order. Works with both sorted() and list.sort(). Persists all benefits of the used sorting method.