Sorted Function in Python
The sorted function in Python is a powerful built-in function that allows you to sort elements from any iterable, such as lists, tuples, or strings. It returns a new list containing all items from the iterable in ascending order by default. The function is highly customizable, offering various sorting behaviors through its parameters, making it a versatile tool for developers.
Basic Usage
The basic syntax of the sorted function is:
sorted(iterable, key=None, reverse=False)
- iterable: The collection of items you want to sort.
- key: A function that serves as a key for the sort comparison. This is optional.
- reverse: A boolean value. If set to
True, the list elements are sorted as if each comparison were reversed.
For example, sorting a tuple in ascending order:
x = (4, 3, 1, 2)
y = sorted(x)
print(y) # Output: [1, 2, 3, 4]
Custom Sorting with Key Parameter
The key parameter allows you to define custom sorting logic by providing a callable (such as a function or a lambda expression) that extracts a comparison key from each element in the iterable. This is particularly useful for sorting complex data structures or custom objects.
Sorting with a Key Function
For instance, sorting a list of dictionaries by specific keys:
import operator
PEOPLE = [{'first': 'Reuven', 'last': 'Lerner', 'email': 'reuven@lerner.co.il'},
{'first': 'Donald', 'last': 'Trump', 'email': 'president@whitehouse.gov'},
{'first': 'Vladimir', 'last': 'Putin', 'email': 'president@kremvax.ru'}]
def alphabetize_names(list_of_dicts):
return sorted(list_of_dicts, key=operator.itemgetter('last', 'first'))
print(alphabetize_names(PEOPLE))
In this example, operator.itemgetter is used to sort the list of dictionaries by the last and first keys.
Sorting by Length
You can also use built-in functions like len as the key function to sort elements by their length:
mylist = ['abcd', 'efg', 'hi', 'j']
mylist = sorted(mylist, key=len)
print(mylist) # Output: ['j', 'hi', 'efg', 'abcd']
Using Lambda Functions
Lambda functions provide a concise way to create anonymous functions for one-time use:
for p in sorted(PEOPLE, key=lambda x: [x['last'], x['first']]):
print(f'{p["last"]}, {p["first"]}: {p["email"]}')
Here, a lambda function is used to sort the list of people by their last and first names.
Practical Applications
The sorted function can be applied in various practical scenarios, such as calculating statistical measures. For example, finding the median temperature from a list of temperatures:
temperatures = [30, 22, 25, 28, 32, 31, 29]
sorted_temps = sorted(temperatures)
mid = len(sorted_temps) // 2
if len(sorted_temps) % 2 == 0:
median_temp = (sorted_temps[mid - 1] + sorted_temps[mid]) / 2
else:
median_temp = sorted_temps[mid]
print("Median temperature:", median_temp)
In this code snippet, sorted() is used to create a sorted copy of the temperatures list, which is then used to calculate the median temperature.
Key Parameter in Other Functions
The key parameter is not exclusive to sorted. It can also be used with other functions like max to determine the criteria for comparison. For example, finding the word with the most repeating letters:
from collections import Counter
WORDS = ['this', 'is', 'an', 'elementary', 'test', 'example']
def most_repeating_letter_count(word):
return Counter(word).most_common(1)[0][1]
def most_repeating_word(words):
return max(words, key=most_repeating_letter_count)
print(most_repeating_word(WORDS))
In this example, most_repeating_letter_count is used as the key function for max, allowing it to find the word with the highest count of repeating letters.
For more detailed examples and explanations, you can refer to the following resources:
| Book Title | Usage of sorted | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|-----------------|-----------------|-------------------------------|---------------|-----------------------|
| [Python Workout](https://www.manning.com/books/python-workout) | Discusses the `sorted` function's versatility, including sorting with a key function and using lambda functions. [more](https://livebook.manning.com/book/python-workout/chapter-3/1) | Explains the use of the `key` parameter for custom sorting, including sorting complex data structures. [more](https://livebook.manning.com/book/python-workout/chapter-3/1) | Connects `sorted` with other functions like `max` using the `key` parameter. [more](https://livebook.manning.com/book/python-workout/chapter-3/1) | Provides examples of sorting lists of dictionaries and sorting by length. [more](https://livebook.manning.com/book/python-workout/chapter-3/1) | Demonstrates practical applications like alphabetizing names and finding words with the most repeating letters. [more](https://livebook.manning.com/book/python-workout/chapter-3/1) |
| [Python How-To](https://www.manning.com/books/python-how-to) | Covers basic usage and customization of the `sorted` function, including sorting custom objects. [more](https://livebook.manning.com/book/python-how-to/chapter-10/233) | Details the `key` and `reverse` parameters for custom sorting logic. [more](https://livebook.manning.com/book/python-how-to/chapter-10/233) | Highlights the use of `sorted` in interactive development environments like IDLE. [more](https://livebook.manning.com/book/python-how-to/chapter-10/233) | Includes examples of sorting numbers by their square values. [more](https://livebook.manning.com/book/python-how-to/chapter-10/233) | Focuses on interactive development, aiding beginners with immediate access to documentation. [more](https://livebook.manning.com/book/python-how-to/chapter-10/233) |
| [The Quick Python Book, Fourth Edition](https://www.manning.com/books/the-quick-python-book-fourth-edition) | Describes the `sorted()` function's ability to handle various iterables and its default ascending order. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-5/93) | Explores custom sorting with the `key` function and the `reverse` parameter. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-5/95) | Demonstrates the use of `sorted()` in statistical calculations, such as finding the median. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-5/247) | Provides examples of sorting tuples and calculating statistical measures. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-5/95) | Shows practical applications in calculating temperatures and statistical measures. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-5/247) |
FAQ (Frequently asked questions)
What does the sorted function do in Python?
What is the key parameter in the sorted function?
Can you use custom sorting logic with the sorted function?
How can you sort poker cards using the sorted function?
Can the sorted function be used on both lists and tuples?
What type of data structure does the sorted function return?
How can you modify the sort order when using the sorted function?
What does the function passed to the key parameter do?
What does the sorted() function do in Python?
Can the sorted() function in Python perform custom sorting?
How can you reverse sort using the sorted() function in Python?
How do you use the sorted() function to sort an iterable in Python?
How can you find the median temperature from a list of temperatures in Python?
What is the purpose of the sorted() function in calculating the median?