The sorted() function helps you put items in order, like sorting names alphabetically or numbers from smallest to largest.
sorted() function in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
sorted(iterable, *, key=None, reverse=False)
iterable can be any group of items like a list, tuple, or string.
key lets you choose a rule for sorting, like sorting by length.
Examples
Python
sorted([3, 1, 2])
Python
sorted(['apple', 'banana', 'cherry'], reverse=True)
Python
sorted(['apple', 'banana', 'cherry'], key=len)
Python
sorted('hello')
Sample Program
This program shows how sorted() keeps the original list the same and creates a new sorted list. It also shows sorting numbers in reverse order.
Python
fruits = ['banana', 'apple', 'cherry'] sorted_fruits = sorted(fruits) print('Original list:', fruits) print('Sorted list:', sorted_fruits) numbers = [5, 2, 9, 1] sorted_numbers = sorted(numbers, reverse=True) print('Numbers sorted from largest to smallest:', sorted_numbers)
Important Notes
sorted() does not change the original list; it makes a new sorted list.
You can sort any iterable, not just lists.
Use reverse=True to sort backwards.
Summary
sorted() arranges items in order and returns a new list.
You can sort by normal order, reverse, or a custom rule with key.
The original data stays the same after sorting.
Practice
1. What does the
sorted() function do in Python?easy
Solution
Step 1: Understand the purpose of
Thesorted()sorted()function creates a new list with the elements arranged in ascending order by default.Step 2: Compare with other options
It does not change the original list, nor does it delete items or return just the largest item.Final Answer:
Returns a new list with items arranged in order -> Option AQuick Check:
sorted()returns new sorted list [OK]
Hint: Remember: sorted() returns a new list, original stays same [OK]
Common Mistakes:
- Thinking sorted() changes the original list
- Confusing sorted() with max() or min()
- Assuming sorted() deletes items
2. Which of the following is the correct syntax to sort a list
nums in reverse order using sorted()?easy
Solution
Step 1: Check the correct parameter for reverse sorting
Thesorted()function uses the keyword argumentreverse=Trueto sort in descending order.Step 2: Validate the parameter type
The value must be the booleanTrue, not False, numbers like 0, or undefined names.Final Answer:
sorted(nums, reverse=True) -> Option DQuick Check:
Use reverse=True (boolean) for descending sort [OK]
Hint: Use reverse=True (boolean), not False/0/undefined [OK]
Common Mistakes:
- Using reverse=False (sorts ascending)
- Passing falsy numbers like 0
- Using undefined lowercase 'false'
3. What is the output of the following code?
words = ['pear', 'apple', 'orange'] sorted_words = sorted(words, key=len) print(sorted_words)
medium
Solution
Step 1: Understand the key parameter
Thekey=lentellssorted()to sort the list by the length of each word.Step 2: Sort words by length
Lengths: 'pear' (4), 'apple' (5), 'orange' (6). Sorted ascending by length: ['pear', 'apple', 'orange'].Final Answer:
['pear', 'apple', 'orange'] -> Option AQuick Check:
sorted(words, key=len) sorts by length ascending [OK]
Hint: key=len sorts items by their length ascending [OK]
Common Mistakes:
- Confusing sorting by value vs length
- Assuming sorted() changes original list
- Misreading the order of output
4. Find the error in this code snippet:
numbers = [3, 1, 4, 1, 5] sorted_numbers = sorted(numbers, key='abs') print(sorted_numbers)
medium
Solution
Step 1: Check the key argument type
Thekeyparameter must be a function, likeabs, not a string.Step 2: Identify the error
Here,key='abs'is a string, which causes a TypeError.Final Answer:
key argument should be a function, not a string -> Option CQuick Check:
key needs a function, not string [OK]
Hint: Pass function to key, not string name [OK]
Common Mistakes:
- Passing string instead of function to key
- Thinking sorted() can't sort numbers
- Forgetting parentheses in function calls
5. You have a list of tuples representing people and their ages:
people = [('Alice', 30), ('Bob', 25), ('Charlie', 35), ('David', 25)]
How do you use sorted() to sort this list by age ascending, and if ages are equal, by name alphabetically?hard
Solution
Step 1: Understand sorting by multiple criteria
To sort by age first, then by name if ages tie, use a tuple key with age first, then name.Step 2: Write the key function
The lambdalambda x: (x[1], x[0])returns a tuple (age, name) for sorting.Step 3: Check other options
The option sorting by name then age is incorrect. Options sorting by only one field are wrong.Final Answer:
sorted(people, key=lambda x: (x[1], x[0])) -> Option BQuick Check:
Use tuple key (age, name) for multi-level sort [OK]
Hint: Use tuple in key: (age, name) for multi-level sorting [OK]
Common Mistakes:
- Sorting by name before age
- Using single key instead of tuple
- Confusing tuple order in key function
