sorted() function in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we use the sorted() function in Python, it rearranges items into order. Knowing how long this takes helps us understand how it behaves with bigger lists.
We want to find out how the time to sort grows as the list gets larger.
Analyze the time complexity of the following code snippet.
numbers = [5, 3, 8, 6, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
This code takes a list of numbers and creates a new list with the numbers sorted from smallest to largest.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing and rearranging elements to sort the list.
- How many times: The sorting process compares elements many times, depending on the list size.
As the list gets bigger, the number of comparisons and moves grows faster than the list size itself.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 35 comparisons |
| 100 | About 700 comparisons |
| 1000 | About 10,000 comparisons |
Pattern observation: When the list size grows 10 times, the work grows roughly 10 times, showing a growth faster than just the list size but consistent with O(n log n).
Time Complexity: O(n log n)
This means the time to sort grows a bit faster than the list size but much slower than if it grew by the square of the list size.
[X] Wrong: "Sorting always takes the same time no matter how big the list is."
[OK] Correct: Sorting takes more time as the list grows because it needs to compare and arrange more items, so bigger lists take longer.
Understanding how sorting time grows helps you explain your code choices clearly and shows you know how your program behaves with bigger data.
"What if we used a list that was already sorted? How would the time complexity change when using sorted()?"
Practice
sorted() function do in Python?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]
- Thinking sorted() changes the original list
- Confusing sorted() with max() or min()
- Assuming sorted() deletes items
nums in reverse order using sorted()?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]
- Using reverse=False (sorts ascending)
- Passing falsy numbers like 0
- Using undefined lowercase 'false'
words = ['pear', 'apple', 'orange'] sorted_words = sorted(words, key=len) print(sorted_words)
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]
- Confusing sorting by value vs length
- Assuming sorted() changes original list
- Misreading the order of output
numbers = [3, 1, 4, 1, 5] sorted_numbers = sorted(numbers, key='abs') print(sorted_numbers)
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]
- Passing string instead of function to key
- Thinking sorted() can't sort numbers
- Forgetting parentheses in function calls
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?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]
- Sorting by name before age
- Using single key instead of tuple
- Confusing tuple order in key function
