Worldscope

Python sorted()

Palavras-chave:

Publicado em: 03/08/2025

Understanding Python's `sorted()` Function

The `sorted()` function in Python is a built-in function used to sort iterable objects (like lists, tuples, strings, dictionaries, and sets) and return a new sorted list. This article will explore the fundamental concepts, usage, complexity, and alternatives for effectively employing `sorted()` in your Python projects.

Fundamental Concepts / Prerequisites

To fully understand the `sorted()` function, a basic understanding of the following is helpful:

  • Iterables: Know what iterables are (objects you can loop over).
  • Lists: Familiarity with Python lists and their properties.
  • Comparisons: An understanding of how Python compares objects using operators like <, >, and ==.
  • Lambda Functions (Optional): Useful for custom sorting criteria but not strictly required.

Core Implementation/Solution

Here's a demonstration of how to use the `sorted()` function:


# Example 1: Sorting a list of numbers
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers)
print(f"Original list: {numbers}")
print(f"Sorted list: {sorted_numbers}")

# Example 2: Sorting a list of strings (alphabetically)
strings = ["apple", "banana", "cherry", "date"]
sorted_strings = sorted(strings)
print(f"Original list: {strings}")
print(f"Sorted list: {sorted_strings}")

# Example 3: Sorting in reverse order
reverse_sorted_numbers = sorted(numbers, reverse=True)
print(f"Reverse sorted list: {reverse_sorted_numbers}")

# Example 4: Sorting a list of tuples based on the second element using a lambda function
tuples = [(1, 'z'), (2, 'a'), (3, 'b')]
sorted_tuples = sorted(tuples, key=lambda x: x[1])
print(f"Original list: {tuples}")
print(f"Sorted list: {sorted_tuples}")

# Example 5: Sorting a dictionary by values
my_dict = {'a': 3, 'b': 1, 'c': 2}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(f"Original dict: {my_dict}")
print(f"Sorted dict: {sorted_dict}")

Code Explanation

Example 1: We create a list of integers called `numbers`. The `sorted(numbers)` function returns a *new* sorted list, which is assigned to `sorted_numbers`. The original list remains unchanged.

Example 2: We create a list of strings called `strings`. The `sorted(strings)` function sorts the strings alphabetically.

Example 3: We use the `reverse=True` argument within `sorted()` to sort the numbers in descending order.

Example 4: We have a list of tuples. We use the `key` argument and a `lambda` function to specify that we want to sort based on the second element (index 1) of each tuple. The `lambda x: x[1]` function takes a tuple `x` as input and returns the second element.

Example 5: Dictionaries are inherently unordered, but you can get a sorted representation of their items. First, `my_dict.items()` gives a list of key-value pairs (tuples). Then we use `sorted` with the `key` parameter to sort these pairs based on their values. Finally, we convert the result back to a dictionary using `dict()`.

Complexity Analysis

The `sorted()` function in Python uses the Timsort algorithm. Timsort is a hybrid sorting algorithm derived from merge sort and insertion sort, designed to perform well on real-world data.

Time Complexity:

  • Best Case: O(n) - When the input is already nearly sorted.
  • Average Case: O(n log n)
  • Worst Case: O(n log n)

Space Complexity:

The space complexity is O(n) because `sorted()` creates a new list to store the sorted elements. In-place sorting algorithms modify the original data structure directly and have less space complexity, but are not what `sorted()` does.

Alternative Approaches

While `sorted()` is a versatile and efficient function, another way to achieve sorting, especially when modification in place is desired is by using the `list.sort()` method.

`list.sort()` method:

The `list.sort()` method sorts the list *in-place* (it modifies the original list directly) and returns `None`. It also uses the Timsort algorithm.


numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort() # Sorts the list in place
print(numbers)

Trade-offs:

  • `sorted()` creates a new sorted list, leaving the original iterable unchanged. This is useful when you need to preserve the original data.
  • `list.sort()` modifies the original list and does not return a new list. This can be more memory-efficient when you don't need the original data.

Conclusion

The `sorted()` function is a powerful and convenient tool in Python for sorting iterables. It offers flexibility with the `key` and `reverse` parameters, making it adaptable to various sorting needs. Understanding its time and space complexity and the alternative `list.sort()` method allows developers to make informed decisions about which sorting approach best suits their specific requirements.