Syntax of sorted() Function
The sorted() function allows you to sort data efficiently. Here's its syntax:
sorted(iterable, key=None, reverse=False)
Parameters
- iterable: The data structure you want to sort, like a list, tuple, or dictionary.
- key (optional): A function that defines the sorting criteria. Default is None.
- reverse (optional): A Boolean value. Set to True for descending order. Default is False.
Return Value
The sorted() function returns a new sorted list without modifying the original iterable.
Sorting in Ascending Order
By default, the sorted() function sorts elements in ascending order. Let’s look at an example:
Example:
# Sorting a list of numbers
numbers = [5, 2, 9, 1, 7]
ascending_sorted = sorted(numbers)
print("Original List:", numbers)
print("Sorted List (Ascending):", ascending_sorted)

You can also try this code with Online Python Compiler
Run Code
Output:
Original List: [5, 2, 9, 1, 7]
Sorted List (Ascending): [1, 2, 5, 7, 9]
Explanation: In this example, the sorted() function returns a new list sorted in ascending order, while the original list remains unchanged.
Sorting Strings
You can also sort strings alphabetically:
# Sorting a list of strings
words = ["apple", "orange", "banana", "grape"]
sorted_words = sorted(words)
print("Sorted Strings:", sorted_words)

You can also try this code with Online Python Compiler
Run Code
Output:
Sorted Strings: ['apple', 'banana', 'grape', 'orange']
Sorting in Descending Order
To sort elements in descending order, you need to set the reverse parameter to True.
Example:
# Sorting a list of numbers in descending order
numbers = [5, 2, 9, 1, 7]
descending_sorted = sorted(numbers, reverse=True)
print("Original List:", numbers)
print("Sorted List (Descending):", descending_sorted)

You can also try this code with Online Python Compiler
Run Code
Output:
Original List: [5, 2, 9, 1, 7]
Sorted List (Descending): [9, 7, 5, 2, 1]
Sorting Strings in Descending Order
# Sorting a list of strings in descending order
words = ["apple", "orange", "banana", "grape"]
descending_words = sorted(words, reverse=True)
print("Sorted Strings (Descending):", descending_words)

You can also try this code with Online Python Compiler
Run CodeOutput:
Sorted Strings (Descending): ['orange', 'grape', 'banana', 'apple']
Sorting Using the Key Parameter
The key parameter allows you to customize sorting criteria by passing a function. This is especially useful when sorting complex data structures like lists of dictionaries or objects.
Example 1: Sorting by String Length
# Sorting strings by their lengths
words = ["apple", "orange", "banana", "grape"]
sorted_by_length = sorted(words, key=len)
print("Sorted by Length:", sorted_by_length)

You can also try this code with Online Python Compiler
Run CodeOutput:
Sorted by Length: ['grape', 'apple', 'orange', 'banana']
Explanation: Here, the key=len argument sorts the strings based on their lengths.
Example 2: Sorting a List of Dictionaries
# Sorting a list of dictionaries by age
students = [
{"name": "Alice", "age": 22},
{"name": "Bob", "age": 19},
{"name": "Charlie", "age": 20}
]
sorted_students = sorted(students, key=lambda x: x['age'])
print("Sorted by Age:", sorted_students)

You can also try this code with Online Python Compiler
Run Code
Output:
Sorted by Age: [{'name': 'Bob', 'age': 19}, {'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 22}]
Explanation: In this example, a lambda function is used as the key to sort the dictionaries by the age field.
Example 3: Case-Insensitive Sorting
When sorting strings, you can use the str.lower method to ignore case sensitivity.
# Case-insensitive string sorting
words = ["banana", "Apple", "orange", "Grape"]
sorted_case_insensitive = sorted(words, key=str.lower)
print("Case-Insensitive Sorted:", sorted_case_insensitive)

You can also try this code with Online Python Compiler
Run Code
Output:
Case-Insensitive Sorted: ['Apple', 'banana', 'Grape', 'orange']
Frequently Asked Questions
Does the sorted() function modify the original list?
No, the sorted() function returns a new sorted list without changing the original iterable.
What happens if the key parameter is not provided?
If key is not specified, the sorted() function sorts the elements based on their natural order (e.g., numerical or alphabetical).
Can the sorted() function sort mixed data types?
No, sorted() cannot sort a list with mixed data types, like integers and strings, as they are incomparable.
Conclusion
The Python sorted() function is a powerful tool for organizing data efficiently. Whether you need to sort numbers, strings, or complex data structures, this function provides flexibility and customization options. We covered sorting in ascending and descending order and discussed how the key parameter can be used for advanced sorting scenarios.