How can I sort one list by values from another list?
PythonLevel: Intermediate
How can I sort one list by values from another list?
Hints
- Identify object types, mutability and execution order.
- Trace a minimal example: which values and references change?
Answer
Merge them into an iterator of tuples, sort the resulting list, and then pick out the element you want.
>>> list1 = ["what", "I'm", "sorting", "by"]
>>> list2 = ["something", "else", "to", "sort"]
>>> pairs = zip(list1, list2)
>>> pairs = sorted(pairs)
>>> pairs
[("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
>>> result = [x[1] for x in pairs]
>>> result
['else', 'sort', 'to', 'something']
Source and licence: Python 3.14.0 Programming FAQ — Python Software Foundation · PSF-2.0