Concepts / Comparing Sequences and Strings

Comparing Sequences and Strings

Tuple comparison proceeds element by element from left to right, stopping as soon as a difference is found.

  • Programming

The First Difference Decides

When Python compares tuples, it checks their elements from left to right. It stops as soon as it finds a difference. Elements after that first difference do not affect the result.

Worked example

Comparing Two Tuples

Determine which tuple comes first when comparing (4, 2, 9) and (4, 7, 1).

  1. 1
    Compare position 1

    The first elements are both 4, so there is no difference yet.

  2. 2
    Compare position 2

    The second elements are 2 and 7. This is the first difference, so the comparison is decided here.

  3. 3
    Ignore position 3

    The third elements, 9 and 1, are not considered because an earlier difference has already determined the ordering.

Result

(4, 2, 9) comes before (4, 7, 1).

First elements4 and 4Second elements2 and 7Tuple order(4, 2, 9) firstThird elementsnot comparedequalfirst differencestop
How does Python compare two tuples from left to right, and what happens to the remaining elements after the first difference is found?

Reading Tuple Order

To predict a sorting result, read each tuple from its first element onward. The first position has the first opportunity to decide the order. If two tuples match there, compare their second positions. Continue only while the earlier positions are equal.

Worked example

Finding the Sorting Order

Arrange the tuple keys (2, 8), (1, 9), and (2, 3) in ascending order.

  1. 1
    Compare first positions

    The tuple beginning with 1 comes before both tuples beginning with 2.

  2. 2
    Resolve the matching first positions

    The remaining two tuples both begin with 2, so compare their second elements, 8 and 3.

  3. 3
    Place the tied-first tuples

    The tuple with second element 3 comes before the tuple with second element 8.

Result

(1, 9), (2, 3), (2, 8)

Key A(2, 8)First position1 before 2Sorted keys(1, 9), (2, 3), (2, 8)Key B(1, 9)Second position3 before 8Key C(2, 3)first positions tiefirst positions tiefirst positionplace firstbreak tie
When several records are sorted by tuple keys, which item is compared first, and how does Python resolve ties using later elements?

Building Multi-Criteria Keys

A tuple can hold several sort criteria in a deliberate order. Put the primary criterion first, the secondary criterion second, and later tie-breaking criteria after that. Sorting these tuples applies the same left-to-right comparison rule to the criteria.

In the real world

Suppose records are represented by names and scores. A derived key such as (score, name) makes score the primary criterion. When two records have the same score, the name becomes the next criterion used to order them.

Position 1primary criterionSorted recordresult of left-to-rightcomparisonPosition 2secondary criterionPosition 3later criterioncompare firstcompare when tiedcompare when earlier positions tie
How do the positions in a tuple map to primary, secondary, and later sorting criteria?

Tracing the DSU Pattern

Definition

The Decorate-Sort-Undecorate pattern, often called DSU, uses tuples to sort by derived values. First, create tuples containing sort keys and the original values. Next, sort the tuples. Finally, extract the original values from the sorted tuples.

Worked example

Sorting by a Derived Score

Use DSU to order the original values alpha, beta, and gamma by the derived scores 3, 1, and 2.

  1. 1
    Decorate

    Create tuples containing each derived score and its original value: (3, alpha), (1, beta), and (2, gamma).

  2. 2
    Sort

    Compare the tuples by their first elements, which are the derived scores. The order of the decorated tuples becomes (1, beta), (2, gamma), (3, alpha).

  3. 3
    Undecorate

    Extract the original values from the sorted tuples and remove the derived scores.

Result

beta, gamma, alpha

Original valuesalpha, beta, gammaDecorated tuples(3, alpha), (1, beta), (2,gamma)Sorted tuples(1, beta), (2, gamma), (3,alpha)Sorted valuesbeta, gamma, alphadecoratesortundecorate
How does each original item become a decorated tuple, move through sorting by derived values, and return to its original form?

Sequences and Strings

The central comparison idea is positional: examine elements from left to right and stop at the first difference. Tuple comparison provides the clearest model for this lesson, and the same way of thinking helps you inspect other sequence-like values by asking which position is compared first and where the first difference appears.

Sequence Amatching first positionsFirst differencedecides orderSequence Bmatching first positionsLater positionsnot reachedcompare left to rightcompare left to rightstop after decision
How does Python compare strings or other sequences element by element, and how is that process related to tuple comparison?

Common Sorting Mistakes

  • Common mistake

    Looking at a later tuple element before checking earlier elements

    What it looks like

    Treating (2, 3) as later than (1, 9) because 3 is smaller than 9

    Why it fails

    The first elements differ, so the first position decides the order before the second position matters.

    Do this instead

    Compare positions from left to right and stop at the first difference.

  • Common mistake

    Assuming every element in a tuple is always examined

    What it looks like

    Using the final value in (4, 2, 9) to compare it with (4, 7, 1)

    Why it fails

    The second elements, 2 and 7, are already different.

    Do this instead

    Once a difference is found, ignore the remaining positions for that comparison.

  • Common mistake

    Expecting reverse=True to reverse only the primary criterion

    Why it fails

    reverse=True reverses comparison for all elements in the tuple, including tie-breaking comparisons.

    Do this instead

    Use a custom key function when different criteria require finer control.

  • Common mistake

    Forgetting the undecorate step in DSU

    Why it fails

    Sorting produces tuples containing both derived keys and original values, but the desired final result may consist only of the original values.

    Do this instead

    After sorting, extract the original values from the decorated tuples.

Practice the Comparison

MEDIUM

Predict the ascending order of these tuple keys: (3, 4), (2, 9), (3, 1), and (2, 5). Explain which positions decide each comparison.

Hints
  • Compare the first elements before looking at the second elements.
  • For the two keys beginning with 2, compare their second elements.
  • For the two keys beginning with 3, compare their second elements.
MEDIUM

Trace a DSU process for the original values red, blue, and green when their derived keys are 2, 3, and 1. Write the decorated tuples, their sorted order, and the final undecorated result.

Hints
  • Place each derived key before its original value.
  • Sort the decorated tuples by their first elements.
  • Remove the derived keys after sorting.

Key Takeaways

  1. 1
    Tuple comparison moves from left to right and stops at the first difference.
  2. 2
    The first tuple position is the primary sorting criterion; later positions resolve ties.
  3. 3
    A tuple can represent several sorting criteria in a chosen order.
  4. 4
    DSU decorates original values with sort keys, sorts the decorated tuples, and then extracts the original values.
  5. 5
    reverse=True reverses every comparison in the tuple, while a custom key function provides finer multi-criteria control.

At a glance

  • Python compares tuples element by element from left to right.
  • The first differing element decides the comparison, so later elements may never be considered.
  • Tuple positions naturally express primary, secondary, and later sorting criteria.
  • The DSU pattern sorts derived tuple keys and then returns the original values.
  • reverse=True affects all tuple elements; use a custom key function for finer control.

More concepts starting with C