Python offers many built-in functions, one of which is the sorted() function. This function can be used to sort a variety of Python data structures including lists, tuples, and dictionaries. The sorted() function takes an iterable as input and returns a sorted list of the elements in that iterable. In this article, we'll explore the sorted() function and provide some examples of how to use it.
Basic Syntax
The basic syntax of the sorted() function is as follows:
|
sorted(iterable, key=None, reverse=False)
|
The iterable parameter is mandatory, and it can be any iterable such as a list, tuple, or dictionary. The optional key parameter can be used to specify a function to be called on each element before sorting. The optional reverse parameter is a boolean value that specifies whether the sorted list should be in descending order.
Examples
Let's take a look at some examples of how to use the sorted() function.
Sorting a List
|
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
|
Output:
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
In this example, we have a list of numbers. We call the sorted() function with the numbers list as the iterable. The sorted() function returns a sorted list of the elements in the numbers list. We store this sorted list in the sorted_numbers variable and print it to the console.
Sorting a Tuple
|
fruits = ('apple', 'banana', 'cherry', 'date', 'elderberry')
sorted_fruits = sorted(fruits)
print(sorted_fruits)
|
Output:
['apple', 'banana', 'cherry', 'date', 'elderberry']
In this example, we have a tuple of fruits. We call the sorted() function with the fruits tuple as the iterable. The sorted() function returns a sorted list of the elements in the fruits tuple. We store this sorted list in the sorted_fruits variable and print it to the console.
Sorting a Dictionary
|
ages = {'Alice': 25, 'Bob': 30, 'Charlie': 35, 'David': 40}
sorted_ages = sorted(ages.items(), key=lambda x: x[1])
print(sorted_ages)
|
Output:
[('Alice', 25), ('Bob', 30), ('Charlie', 35), ('David', 40)]
In this example, we have a dictionary of ages. We call the sorted() function with the ages.items() as the iterable. We use the key parameter to specify a lambda function that sorts the dictionary by the values (i.e., the ages) rather than by the keys (i.e., the names). The sorted() function returns a sorted list of the elements in the ages dictionary. We store this sorted list in the sorted_ages variable and print it to the console.
Conclusion
In conclusion, the sorted() function is a powerful built-in function in Python that can be used to sort a variety of Python data structures. It is easy to use and can be used with optional parameters to customize the sorting process.