Concepts / List Methods and Sorting

List Methods and Sorting

Put the frequency first in each tuple. The first tuple element becomes the primary sorting criterion.

  • 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 Counts to Rankings

A word-frequency dictionary answers the question “How many times did each word appear?” Its words are keys and its counts are values. To answer a different question—“Which words appeared most often?”—you need the counts to control the ordering. The useful pattern is to build a list of tuples in the form (count, word), sort that list, and then display the first few tuples.

Key point

Put the frequency first in each tuple. The first tuple element becomes the primary sorting criterion.

The Data Flow

The complete process has distinct stages. The program reads text, builds a dictionary of word counts, restructures each dictionary entry as a (count, word) tuple, sorts the tuple list in reverse order, selects a prefix of that list, and unpacks each selected tuple for display. Keeping these stages separate makes the final output easier to understand and debug.

Input filetextFrequency dictionaryword: countTuple list(count, word)Sorted tupleshighest counts firstTop N slicefirst N tuplesDisplayed resultscount and wordcount wordsrestructure entriessort reverseselect first Nunpack tuples
How does data move from the input file through counting, tuple conversion, sorting, slicing, and final display?

Rebuilding the Sortable Structure

A dictionary stores words as keys and frequencies as values. Sorting the dictionary by its keys would organize words, not frequencies. Instead, create a separate list and place each value before its key. A dictionary entry such as word: frequency becomes the tuple (frequency, word). The original dictionary remains unchanged; the list is a new sortable representation.

thekey5first tuple element5valuethesecond tuple elementmoves after valuemoves before key
What changes when a dictionary shaped as word: frequency is transformed into tuples shaped as (frequency, word)?
Worked example

Dictionary Entries Become Sortable Tuples

Restructure the frequency entries the: 5, to: 5, and i: 61 so that the counts become the primary sort elements.

  1. 1
    Start with key-value entries

    Each entry has a word as its key and a frequency as its value.

  2. 2
    Reverse the positions

    Represent each entry as (count, word), producing (5, the), (5, to), and (61, i).

  3. 3
    Prepare for sorting

    The count is now the first tuple element, so tuple sorting compares frequency before the word.

Result

The sortable list is [(5, the), (5, to), (61, i)] before ordering.

Reverse Order and Ties

Calling sort(reverse=True) sorts the entire tuple in descending order. Python first compares the tuple's first element, so larger counts come first. If two counts match, Python compares the second elements. Because the whole tuple is being sorted in reverse order, the words are then ordered in reverse alphabetical order.

(5, to)count 5, word totoreverse alphabetical order(5, the)count 5, word theappears firstappears after to
When two tuples have the same frequency, which word comes first under reverse sorting?
Worked example

A Tie Uses the Word

Order the tuples (5, the), (5, to), and (61, i) with reverse sorting.

  1. 1
    Compare counts

    The tuple containing 61 comes before the tuples containing 5 because 61 is the larger first element.

  2. 2
    Resolve the equal counts

    The remaining tuples both begin with 5, so Python compares the words to and the.

  3. 3
    Apply reverse alphabetical order

    to comes after the alphabetically earlier word the, so to appears first when the order is reversed.

Result

The order is (61, i), (5, to), (5, the).

Selecting the Top Results

After sorting, the most frequent words are at the beginning of the list. The slice lst[:10] starts at index 0 and stops before index 10, so it selects indices 0 through 9. In a loop written as for count, word in lst[:10]:, each tuple is unpacked: its first element is assigned to count and its second element to word.

Sorted tuple listindex 0, 1, 2, ...lst[:10]indices 0 through 9(count, word)one selected tuplecount, wordfirst and second elementstake first 10visit each tupleunpack
How does a slice select the first N tuples, and how are the tuple elements assigned to loop variables?
python
Output
61 i
42 and
5 to

Tracing a Complete Program

A complete word-frequency program combines file reading, dictionary building, tuple construction, sorting, slicing, and output formatting. The important point is not one particular file-reading implementation; it is the order in which the data changes shape. Text begins as input, becomes word counts, becomes sortable tuples, and finally becomes a short ranked display.

Code walkthrough
counts = {"i": 61, "and": 42, "the": 5, "to": 5}

ranked = []
for word, count in counts.items():
    ranked.append((count, word))

ranked.sort(reverse=True)

for count, word in ranked[:3]:
    print(count, word)
  1. 1
    The counts dictionary represents the result of counting words from input text.
  2. 2
    ranked begins as a separate list, so the original dictionary is not modified.
  3. 3
    The loop creates tuples shaped as (count, word).
  4. 4
    sort(reverse=True) orders the tuples by descending count, then by reverse alphabetical word order for ties.
  5. 5
    ranked[:3] selects the first three tuples.
  6. 6
    The loop unpacks each selected tuple and displays its count and word.
  • The dictionary stores words as keys and counts as values.
  • Each entry is converted to a tuple with the count first.
  • Reverse sorting places higher counts first and resolves equal counts using the words.
  • The slice selects the first three tuples.
  • Tuple unpacking assigns each tuple's count and word to the loop variables.
Output
61 i
42 and
5 to

In the source program's Romeo and Juliet result, i appears 61 times and and appears 42 times. The displayed words are ordered with the highest frequency first. The smaller example above follows the same ranking logic while using fewer entries so that every stage can be traced directly.

Mistakes with Ranked Lists

  • Common mistake

    Sorting the word keys instead of the frequency values

    What it looks like

    Treating the dictionary's words as the values to rank.

    Why it fails

    The question is which words have the largest counts, so alphabetical word order is not the primary criterion.

    Do this instead

    Create (count, word) tuples so the count is the first element.

  • Common mistake

    Putting the word before the count

    What it looks like

    Creating tuples shaped as (word, count).

    Why it fails

    Tuple sorting would compare the word first, making the frequency secondary.

    Do this instead

    Use the (count, word) arrangement.

  • Common mistake

    Expecting ties to remain in an unspecified order

    What it looks like

    Assuming that two words with count 5 can appear in any order.

    Why it fails

    Python compares the second tuple elements when the counts match.

    Do this instead

    Expect reverse alphabetical ordering of the words when sort(reverse=True) is used.

  • Common mistake

    Reading lst[:10] as including index 10

    What it looks like

    Expecting eleven tuples from indices 0 through 10.

    Why it fails

    The ending index of this slice is excluded.

    Do this instead

    Interpret lst[:10] as indices 0 through 9.

  • Common mistake

    Forgetting the tuple's element order during unpacking

    What it looks like

    Using for word, count in ranked[:10]: when tuples are (count, word).

    Why it fails

    The first loop variable receives the first tuple element.

    Do this instead

    Use for count, word in ranked[:10]: when the tuples are (count, word).

Practice the Transformation

MEDIUM

Given the frequency entries {"blue": 3, "red": 7, "green": 3}, describe the tuple list you would build, the order produced by reverse sorting, and the output produced by displaying the first two tuples.

Hints
  • Place each frequency before its word.
  • Compare the frequencies first.
  • For the equal frequencies, compare the words in reverse alphabetical order.
  • The first two positions are selected by the slice [:2].

What do you think happens?

After converting the entries to tuples and sorting in reverse order, which word comes first among the two words with frequency 3?

  • blue

  • green

Reveal answer
Answer:

green

Both tuples have the same first element, 3. Python compares the words next, and reverse alphabetical order places green before blue.

Key Takeaways

  1. 1
    A frequency dictionary stores words as keys and counts as values, but ranking by frequency requires a new sortable structure.
  2. 2
    Represent each entry as (count, word) so the count is the primary tuple-sorting element.
  3. 3
    sort(reverse=True) puts larger counts first and uses reverse alphabetical word order to resolve equal counts.
  4. 4
    The slice lst[:10] selects the first ten positions, and tuple unpacking assigns each tuple's count and word to loop variables.
  5. 5
    The pattern separates counting, restructuring, sorting, selecting, and displaying into clear stages.

At a glance

  • Convert dictionary entries from word: count into (count, word) tuples.
  • Sort the tuple list in reverse order to place the highest frequencies first.
  • When counts tie, Python compares the words and reverse sorting produces reverse alphabetical order.
  • Use slicing to choose the top N tuples and tuple unpacking to display their elements.
  • The complete word-frequency workflow moves through counting, tuple conversion, sorting, slicing, and output.

More concepts starting with L