Python sorted()
Function
The sorted() function in Python is used to sort elements of any iterable (like a list, tuple, or string) and return a new sorted list. It does not modify the original data.
Syntax
sorted(iterable, *, key=None, reverse=False)
Parameters:
iterable
– The sequence to be sorted (like list, tuple, set, dictionary keys, string, etc.)key
(optional) – A function to customize sorting logicreverse
(optional) – IfTrue
, sorts in descending order
Returns:
- A new sorted list.
Example 1: Sorting a List
numbers = [4, 2, 9, 1]
print(sorted(numbers))
[1, 2, 4, 9]
Example 2: Sorting in Reverse Order
numbers = [4, 2, 9, 1]
print(sorted(numbers, reverse=True))
[9, 4, 2, 1]
Example 3: Sorting Strings Alphabetically
fruits = ["banana", "apple", "cherry"]
print(sorted(fruits))
['apple', 'banana', 'cherry']
Example 4: Sorting with a Key Function
# Sort by length of strings
words = ["apple", "banana", "fig", "date"]
print(sorted(words, key=len))
['fig', 'date', 'apple', 'banana']
Example 5: Sorting Tuples by Second Element
pairs = [(1, 3), (2, 2), (4, 1)]
print(sorted(pairs, key=lambda x: x[1]))
[(4, 1), (2, 2), (1, 3)]
Use Cases
- Alphabetical sorting of names or words
- Sorting numbers for comparisons
- Custom sorting using
key
, like sorting objects by attributes - Sorting dictionary keys or values
Common Mistakes
- Expecting
sorted()
to change the original list – it returns a new one - For descending order, forgetting to use
reverse=True
- Passing non-iterable values like integers
Interview Tip
Use sorted()
with custom key
functions to solve problems like sorting students by grades, or sorting tuples by second item.
Summary
sorted()
returns a new sorted list from any iterable- Supports
key
for custom sort logic - Set
reverse=True
for descending order
Practice Problem
Write a program that reads 5 space-separated numbers and prints them in descending order.
nums = list(map(int, input("Enter 5 numbers: ").split()))
sorted_nums = sorted(nums, reverse=True)
print("Sorted descending:", sorted_nums)