Concepts / Sorting Lists with .sort() and sorted()

Sorting Lists with .sort() and sorted()

Sorting the tuple pairs does not separate the keys from their values. The pair (apple, 2) remains one tuple after sorting; only its position in the list changes.

  • 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…

From Dictionary to Sortable Data

A dictionary contains key-value pairs, but the sorting operation in this lesson is performed on a list. The bridge between these two structures is list(d.items()). It takes the dictionary's items and represents them as a list of tuples, so the pairs can be sorted as list elements.

dictionarykey-value pairsd.items()dictionary itemslist of tuples(key, value) pairsexpose itemslist(...)
How does dictionary key-value data flow into a list of tuples?
Worked example

Preparing Dictionary Contents

Suppose d contains the key-value pairs pear: 4, apple: 2, and orange: 3. What structure does list(d.items()) create?

  1. 1
    Start with the dictionary

    The data is held as key-value pairs.

  2. 2
    Read the items

    d.items() provides the dictionary items for conversion.

  3. 3
    Create the list

    list(d.items()) represents each key-value pair as a tuple inside a list.

Result

The resulting list contains the tuples (pear, 4), (apple, 2), and (orange, 3), with each key at position 0 and each value at position 1.

Why Tuple Position Matters

Each tuple produced from a dictionary item has two positions. The key is at index 0, and the value is at index 1. When .sort() is called on the list of tuples, Python sorts by the first element by default. Because the first element is the key, the default result is an ascending alphabetical order of keys.

(apple, 2)tupleappleindex 0: compared first2index 1: valuefirst elementsecond element
What does each tuple contain, and which tuple element does Python compare first?
Tuple positionContentsRole in the default sort
Index 0Dictionary keyCompared first
Index 1Dictionary valueNot used first when sorting by default

The tuple layout explains why dictionary contents sort by key.

Alphabetical Key Order

Consider a list containing the generated tuple pairs (pear, 4), (apple, 2), and (orange, 3). The keys are pear, apple, and orange. Since .sort() examines the first element of each tuple, the pairs move into the order apple, orange, pear. The values stay attached to their original keys because each key and value remains inside the same tuple.

(apple, 2)key: apple(orange, 3)key: orange(pear, 4)key: pearnextnext
What order do the tuple pairs take when Python compares their keys alphabetically?
Key point

Sorting the tuple pairs does not separate the keys from their values. The pair (apple, 2) remains one tuple after sorting; only its position in the list changes.

Choosing .sort() or sorted()

OperationWhat it works withResult
.sort()The list of tuplesSorts that list
sorted()The data being sortedProvides a separately sorted list

Both names describe sorting, but the operations are distinguished by whether the existing list is sorted or a separate sorted list is obtained.

.sort()existing listsorted listthe list is sortedsorted()separate resultsorted listseparate listsortsprovides
Which operation changes the existing list, and which operation creates and returns a separately sorted list?

The Dictionary Stays Unchanged

list(d.items()) creates a list representation of the dictionary's items. Sorting that list changes the order of the tuple elements in the list, not the dictionary itself. The original dictionary remains separate from the sorted list.

dictionarysource key-value pairsdictionarysame dictionarytuple listitems before sortingtuple listsorted by keyunchangedsorted
What remains unchanged in the dictionary after its items have been copied into and sorted as a separate list?
Best practice

When checking whether a sort changed your data, identify which object you passed to the sorting operation. If it was the list created from d.items(), inspect that list separately from the original dictionary.

Mistakes to Avoid

  • Common mistake

    Trying to sort the dictionary contents without first converting the items to a list of tuples.

    What it looks like

    Treating d itself as though it were already the list being sorted.

    Why it fails

    The described sorting process uses list(d.items()) to create the sortable list.

    Do this instead

    Convert the items with list(d.items()), then sort the resulting list.

  • Common mistake

    Assuming the value controls the default order.

    What it looks like

    Expecting a pair with a smaller value to appear first even when its key comes later alphabetically.

    Why it fails

    Each tuple stores the key at index 0, and .sort() compares the first tuple element by default.

    Do this instead

    Look at the keys first when predicting the default order.

  • Common mistake

    Expecting the original dictionary to be reordered by sorting the tuple list.

    What it looks like

    Sorting the list from d.items() and then assuming d itself was modified.

    Why it fails

    The sorted list is separate from the original dictionary.

    Do this instead

    Treat the sorted tuple list and the dictionary as separate objects.

MEDIUM

A dictionary has the generated items banana: 5, apple: 8, and cherry: 2. Describe the list of tuples produced by list(d.items()), then state the alphabetical order of the tuple keys after the list is sorted by default. Finally, explain whether the original dictionary is modified.

Hints
  • Each dictionary item becomes one tuple.
  • The key is at tuple index 0.
  • The original dictionary and the sorted tuple list are separate.

Key Takeaways

  1. 1
    Use list(d.items()) to represent dictionary contents as a list of key-value tuples.
  2. 2
    Each tuple places the key at index 0 and the value at index 1.
  3. 3
    The default .sort() order uses the first tuple element, so tuple pairs are ordered by key alphabetically.
  4. 4
    The list of tuples is separate from the original dictionary, so sorting the list does not modify the dictionary.
  5. 5
    .sort() sorts the existing list, while sorted() provides a separately sorted list.

At a glance

  • Convert dictionary items with list(d.items()) before sorting them as a list.
  • A tuple stores its key first and its value second.
  • Default sorting of the tuple list compares keys in ascending alphabetical order.
  • Sorting the tuple list does not modify the original dictionary.
  • .sort() operates on an existing list, whereas sorted() provides a separate sorted list.

Related concepts

More concepts starting with S