What is the use of the "sorted" function in Python?
Table of Contants
Introduction
The sorted
function in Python is a built-in utility that returns a new list containing all items from an iterable, sorted in ascending order by default. It provides a convenient way to sort elements without modifying the original iterable, making it versatile for various data manipulation tasks.
How the sorted
Function Works
The sorted
function can sort any iterable (such as lists, tuples, and strings) and returns a new list with the elements sorted.
Syntax:
iterable
: The iterable to be sorted (e.g., list, tuple, string).key
(optional): A function that takes an element and returns a value to be used for sorting. The default isNone
, which means sorting is based on the elements' natural ordering.reverse
(optional): A boolean value indicating whether to sort in descending order. The default isFalse
, which sorts in ascending order.
Example:
Output:
In this example, sorted
returns a new list with the numbers sorted in ascending order.
Using the key
Parameter
The key
parameter allows you to specify a function to determine the sorting criteria.
Example:
Output:
Here, sorted
uses the length of each word for sorting, resulting in words arranged by length.
Using the reverse
Parameter
The reverse
parameter allows you to sort in descending order.
Example:
Output:
In this example, sorted
returns a list sorted in descending order.
Comparing sorted
with sort
-
sorted
: Returns a new sorted list and does not modify the original iterable. -
sort
: Modifies the list in place and does not return a new list.
Example Comparison:
Here, sorted
does not alter the original list, while sort
modifies the list in place.
Practical Examples
1. Sorting a List of Tuples
Output:
In this example, sorted
sorts a list of tuples by the second element of each tuple (the fruit names).
2. Sorting Strings Alphabetically
Output:
Here, sorted
arranges the strings in alphabetical order.
3. Sorting with Custom Criteria
Output:
In this example, sorted
orders students by their scores in descending order.
Conclusion
The sorted
function in Python is a powerful tool for sorting iterables and creating new lists in a specified order. It offers flexibility with its key
and reverse
parameters, making it suitable for a wide range of sorting tasks. Understanding how to use sorted
effectively can enhance your data manipulation capabilities and improve the efficiency of your Python programs.