Bird
Raised Fist0
Pythonprogramming~10 mins

sorted() function in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - sorted() function
Start with iterable
Call sorted()
Compare elements
Arrange elements in order
Return new sorted list
End
The sorted() function takes an iterable, compares its elements, arranges them in order, and returns a new sorted list.
Execution Sample
Python
numbers = [3, 1, 4, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
This code sorts the list 'numbers' and prints the sorted list.
Execution Table
StepActionIterable StateComparisonResult
1Start with numbers = [3, 1, 4, 1][3, 1, 4, 1]N/AN/A
2Call sorted(numbers)[3, 1, 4, 1]Compare 3 and 11 < 3, so 1 comes first
3Compare 3 and 4[3, 1, 4, 1]3 < 43 comes before 4
4Compare 1 and 3[3, 1, 4, 1]1 < 31 comes before 3
5Arrange elements[3, 1, 4, 1]N/A[1, 1, 3, 4]
6Return new sorted list[3, 1, 4, 1]N/A[1, 1, 3, 4]
7Print sorted_numbers[3, 1, 4, 1]N/AOutput: [1, 1, 3, 4]
💡 All elements compared and arranged; sorted() returns new sorted list.
Variable Tracker
VariableStartAfter sorted()Final
numbers[3, 1, 4, 1][3, 1, 4, 1][3, 1, 4, 1]
sorted_numbersN/A[1, 1, 3, 4][1, 1, 3, 4]
Key Moments - 3 Insights
Does sorted() change the original list?
No, sorted() returns a new sorted list and does not modify the original list 'numbers' as shown in variable_tracker rows 1 and 2.
What type of object does sorted() return?
sorted() always returns a new list, even if the input is another iterable type, as shown in execution_table step 6.
Why do we see multiple comparisons in the execution_table?
sorted() compares elements pairwise to decide their order, which is why steps 2 to 4 show comparisons before arranging the final list.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5, what is the arranged list?
A[4, 3, 1, 1]
B[1, 1, 3, 4]
C[3, 1, 4, 1]
D[1, 3, 1, 4]
💡 Hint
Check the 'Result' column at step 5 in the execution_table.
According to variable_tracker, what is the value of 'numbers' after sorted() is called?
A[3, 1, 4, 1]
B[1, 1, 3, 4]
CN/A
D[]
💡 Hint
Look at the 'numbers' row in variable_tracker after sorted() call.
If we change 'numbers' to a tuple, what will sorted() return?
AA sorted tuple
BAn error
CA sorted list
DThe original tuple unchanged
💡 Hint
Recall that sorted() always returns a list regardless of input type.
Concept Snapshot
sorted(iterable) returns a new list with elements sorted in ascending order.
It does not change the original iterable.
Works with any iterable (list, tuple, string).
You can provide key and reverse parameters for custom sorting.
Always returns a list.
Full Transcript
The sorted() function takes an iterable like a list and returns a new list with the elements arranged in ascending order. It compares elements pairwise to decide their order. The original list remains unchanged. The returned object is always a list, even if the input is a tuple or string. This example shows sorting a list of numbers and printing the sorted result.

Practice

(1/5)
1. What does the sorted() function do in Python?
easy
A. Returns a new list with items arranged in order
B. Changes the original list to be sorted
C. Deletes all items from the list
D. Returns the largest item in the list

Solution

  1. Step 1: Understand the purpose of sorted()

    The sorted() function creates a new list with the elements arranged in ascending order by default.
  2. Step 2: Compare with other options

    It does not change the original list, nor does it delete items or return just the largest item.
  3. Final Answer:

    Returns a new list with items arranged in order -> Option A
  4. Quick 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
A. sorted(nums, reverse=False)
B. sorted(nums, reverse=0)
C. sorted(nums, reverse=false)
D. sorted(nums, reverse=True)

Solution

  1. Step 1: Check the correct parameter for reverse sorting

    The sorted() function uses the keyword argument reverse=True to sort in descending order.
  2. Step 2: Validate the parameter type

    The value must be the boolean True, not False, numbers like 0, or undefined names.
  3. Final Answer:

    sorted(nums, reverse=True) -> Option D
  4. Quick 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
A. ['pear', 'apple', 'orange']
B. ['pear', 'apple', 'orange'] sorted by length
C. ['apple', 'orange', 'pear']
D. ['pear', 'apple', 'orange'] sorted by length ascending

Solution

  1. Step 1: Understand the key parameter

    The key=len tells sorted() to sort the list by the length of each word.
  2. Step 2: Sort words by length

    Lengths: 'pear' (4), 'apple' (5), 'orange' (6). Sorted ascending by length: ['pear', 'apple', 'orange'].
  3. Final Answer:

    ['pear', 'apple', 'orange'] -> Option A
  4. Quick 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
A. sorted() cannot sort numbers
B. Missing parentheses after sorted
C. key argument should be a function, not a string
D. reverse argument is required

Solution

  1. Step 1: Check the key argument type

    The key parameter must be a function, like abs, not a string.
  2. Step 2: Identify the error

    Here, key='abs' is a string, which causes a TypeError.
  3. Final Answer:

    key argument should be a function, not a string -> Option C
  4. Quick 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
A. sorted(people, key=lambda x: (x[0], x[1]))
B. sorted(people, key=lambda x: (x[1], x[0]))
C. sorted(people, key=lambda x: x[1])
D. sorted(people, key=lambda x: x[0])

Solution

  1. 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.
  2. Step 2: Write the key function

    The lambda lambda x: (x[1], x[0]) returns a tuple (age, name) for sorting.
  3. Step 3: Check other options

    The option sorting by name then age is incorrect. Options sorting by only one field are wrong.
  4. Final Answer:

    sorted(people, key=lambda x: (x[1], x[0])) -> Option B
  5. Quick 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