Sort 2 lists in Python based on the ratio of individual corresponding elements or based on a third list
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
When two or more Python lists represent aligned rows of data, the most important rule is to sort them together, not separately. If you sort each list independently, you destroy the relationship between corresponding elements. The safe pattern is to combine aligned values, sort once with a clear key, and then unpack the result if you still need separate lists afterward.
Sort by the Ratio of Corresponding Elements
Suppose you have two lists a and b, and you want the ordering to depend on a[i] / b[i]. Zip the lists into row pairs first, then sort by a ratio key.
That keeps row alignment intact because Python sorts whole pairs instead of separate values.
The same idea works for descending order:
Handle Division by Zero Explicitly
Ratio-based sorting needs a policy for b[i] == 0. Do not leave that undefined.
Other valid policies include:
- reject the row with an exception
- filter zero-denominator rows before sorting
- treat them as lowest priority instead of highest
The right choice depends on the business meaning of the data.
Sort Two Lists Based on a Third List
If the ordering is determined by a separate ranking list, zip all three aligned sequences and sort on that third value.
This is the general solution whenever several lists form one logical table.
Index-Based Sorting Is Another Good Pattern
Sometimes you do not want to zip and unzip the data. In that case, compute sorted indices and apply them to every list.
This is useful when you have many aligned lists and want one shared ordering vector.
Prefer Tabular Structures When the Data Is Really Tabular
If you already have multiple related columns, a table abstraction is often easier to maintain than manually managing several lists.
With pandas, the same operation becomes clearer:
For anything beyond a few small lists, this is usually more readable than repeated zip logic.
Common Pitfalls
- Sorting aligned lists independently and breaking row relationships.
- Ignoring division-by-zero behavior in ratio sorting.
- Forgetting that string values such as
"10"and"2"sort lexically unless converted. - Skipping length validation when lists are supposed to be aligned.
- Using separate sort keys for separate lists when one shared ordering is required.
Summary
- Combine aligned lists before sorting so row relationships stay intact.
- For ratio sorting, sort zipped pairs using a ratio key.
- Define zero-denominator behavior explicitly.
- When ordering depends on a third list, zip all aligned sequences and sort by that field.
- If the data is really tabular, a DataFrame is often cleaner than several parallel lists.

