How to sort 2d array by row in python?

Python, per se, has no “2d array” — it has (1d) lists as built-ins, and (1d) arrays in standard library module array. There are third-party libraries such as numpy which do provide Python-usable multi-dimensional arrays, but of course you’d be mentioning such third party libraries if you were using some of them, rather than just saying “in Python”, right?-)

So I’ll assume that by “2d array” you mean a list of lists, such as:

lol = [ range(10), range(2, 12), range(5, 15) ]

or the like — i.e. a list with 3 items, each item being a list with 10 items, and the “second row” would be the sublist item lol[1]. Yeah, lots of assumptions, but your question is so maddeningly vague that there’s no way to avoid making assumptions – edit your Q to clarify with more precision, and an example!, if you dislike people trying to read your mind (and probably failing) as you currently make it impossible to avoid.

So under these assumptions you can sort each of the 3 sublists in the order required to sort the second one, for example:

indices = range(10)
indices.sort(key = lol[1].__getitem__)
for i, sublist in enumerate(lol):
  lol[i] = [sublist[j] for j in indices]

The general approach here is to sort the range of indices, then just use that appropriately sorted range to reorder all the sublists in play.

If you actually have a different problem, there will of course be different solutions;-).

Leave a Comment