Passion is like genius; a miracle.

Blog on Software, Statistics, and Quant

Sorting two arrays at once in Python


If two arrays should be sorted with the same criteria, use zip.

>>> x1 = ['c', 'a', 'b']
>>> y1 = [3, 1, 2]
>>> z = zip(x1, y1)
>>> z.sort()
>>> z
[('a', 1), ('b', 2), ('c', 3)]
>>> # Because zip returns tuples, we need to convert them to lists.
>>> x2, y2 = map(lambda x: list(x), zip(*z))
>>> x2
['a', 'b', 'c']
>>> y2
[1, 2, 3]


2 responses to “Sorting two arrays at once in Python”

  1. cozy5f Avatar

    Suppose Python 2.

    map(lambda x: list(x), zip(*z)) could be map(list, zip(*z)).

    Even zip(*z) is sufficient if tuples are OK.

  2. cozy5f Avatar

    Great, anyway!

Leave a Reply

Your email address will not be published. Required fields are marked *