Concepts / Working with Sorted Data: The sorted() Function

Working with Sorted Data: The sorted() Function

To predict the list's state, keep the list's elements and arrange them in ascending order. The list changes from its original ordering to the sorted ordering.

  • Programming
Interactive lab

Try it: Sorting with key= and reverse=

How sorted() and list.sort() compute key(item) once per item, order the items by those keys with Python's comparison rules, and keep equal keys in their original order — including py4e's sort-a-dict-by-value pattern.

How it works

  1. Decorate: call the key function once on every item (no key means the item itself is compared).
  2. Compare keys with Python's rules: ints by value, strs by code point ('Z' < 'a'), tuples item by item.
  3. Order the items by key; reverse=True puts the largest key first.
  4. Stable: items with equal keys keep their original relative order, also with reverse=True.
  5. sorted() returns a new list; list.sort() rearranges the list in place and returns None; [:N] keeps the first N.

Default run (12 steps): 5 items in their original order. Python will call lambda t: t[1] once per item. … sorted() returned a new list: result = [('fig', 5), ('kiwi', 5), ('pear', 3), ('apple', 3), ('date', 1)].

Simplified: Up to 10 items of one kind (ints, short ASCII words, (word, count) tuples or a small dict) and a fixed menu of key functions. The sorting algorithm itself (Timsort) is not shown — only what it guarantees: the order by key and stability.

Educational simulation

Loading the simulation…

A List Before Sorting

Imagine a list named t containing the values 3, 1, and 2. The values are not yet in ascending order. Calling the sort() method arranges those elements from the smallest value to the largest value. The important detail is that sort() changes the existing list rather than producing a separate sorted list value.

What do you think happens?

After calling sort() on a list containing 3, 1, and 2, what will the list contain?

  • 3, 1, 2

  • 1, 2, 3

  • None

Reveal answer
Answer:

The list will contain 1, 2, 3.

The sort() method arranges list elements in ascending order. It modifies the list in place, so the existing list now contains the ordered elements.

The In-Place Change

In place means that sort() modifies the list it is called on. Before the call, the list has its original order. After the call, that same list has its elements arranged in ascending order. The method does not require you to replace the list variable with a new sorted value. You call the method on the list, and the list's contents change directly.

[3, 1, 2]before sort()[1, 2, 3]after sort()sort()
What does the list contain before and after sort() is called?
Key point

To predict the list's state, keep the list's elements and arrange them in ascending order. The list changes from its original ordering to the sorted ordering.

Void Methods and Returned Values

Definition

A void method modifies an object and returns None rather than returning a new value. The sort() method is a void method: its job is to arrange the elements of the list in place.

This creates two separate ideas to track. First, the list is changed and ends up in ascending order. Second, the result produced by calling sort() is None. The sorted list is the modified object; it is not the return value of the method.

Existing listmodified in placeMethodreturns a new valuesort()returns NoneNew valueseparate resultAscending listsame list after changecallchanges toreturns
What is the difference between a method that changes an existing list and a method that produces a separate sorted value?

The Assignment Trap

The critical mistake is assigning the result of sort() back to the list variable. For example, if t refers to a list, writing t = t.sort() first sorts the list, but then assigns the method's return value to t. Because sort() returns None, t is overwritten with None.

tlist valuesort()modifies the listNonereturn valuetNonecallreturnsassigned to
What happens to the variable when code assigns the result of list.sort() back to it?
  • Common mistake

    Writing t = t.sort()

    What it looks like

    A list is sorted, but the variable t is then assigned the method's return value.

    Why it fails

    sort() returns None, not a new sorted list. The assignment overwrites t with None.

    Do this instead

    Call the method without assignment: t.sort().

  • Common mistake

    Assuming that every method call supplies a replacement value

    What it looks like

    Treating the result of sort() as though it were a separate sorted list.

    Why it fails

    Void methods modify an object and return None.

    Do this instead

    Check whether the method changes the object in place or returns a new value before assigning its result.

Before
t = t.sort()

The list is sorted, then t receives None.

After
t.sort()

The list is sorted and t continues to refer to the modified list.

Tracking Element Positions

Sorting changes the positions of elements when their original order is not ascending. For a list containing 3, 1, and 2, the value at the first position changes from 3 to 1, the value at the second position changes from 1 to 2, and the value at the third position changes from 2 to 3. The elements are the same values; their order has changed.

index 03index 01index 11index 12index 22index 23sort()sort()sort()
How do the positions of list elements change after sort() arranges them in ascending order?
Worked example

Predicting the Final List

A list contains 8, 4, and 6. What will it contain after sort() is called?

  1. 1
    Identify the values

    The list contains 8, 4, and 6.

  2. 2
    Arrange in ascending order

    Place the smallest value first, followed by the next value, then the largest value.

  3. 3
    Track the in-place change

    The existing list is modified; a separate replacement list is not required.

Result

The list contains 4, 6, and 8 after sort() is called.

Using sort() Correctly

Best practice

Always call the void method without assignment: t.sort(). After the call, reason about two facts separately: t's list has been arranged in ascending order, and sort() itself returned None. This habit prevents the assignment mistake and makes the list's final state predictable.

EASY

A list contains 9, 2, and 5. Predict both the list's contents and the variable's state after calling sort() without assignment. Then predict what happens if the result is assigned back to the variable.

Hints
  • Arrange the values from smallest to largest.
  • Remember that sort() modifies the list in place.
  • Remember that a void method returns None.

Key Takeaways

  1. 1
    sort() arranges list elements in ascending order.
  2. 2
    sort() modifies the existing list in place.
  3. 3
    A void method modifies an object and returns None rather than a new value.
  4. 4
    Call sort() without assignment: t.sort().
  5. 5
    Writing t = t.sort() overwrites t with None.

At a glance

  • The sort() method arranges list elements in ascending order.
  • The method changes the existing list rather than returning a new sorted value.
  • Because sort() is a void method, it returns None.
  • Use t.sort() without assignment; assigning t = t.sort() overwrites the variable with None.
  • You can predict the final list by arranging its existing elements in ascending order.

Related concepts

More concepts starting with W