Sort a list by negative numbers, zeros, then positive Python


How do I make a new list where the numbers are sorted first in negative, then 0’s and then positive numbers in Python?

For example if I have the list a = [3, -5, 1, 0, -1, 0, -2]
I want the new list to be [-5, -1, -2, 0, 0, 3, 1]

Asked By: May



You can set a sort key:

a.sort(key=lambda i:1 if i>0 else 0 if i==0 else -1)

You can change this to split by any predicate.

Answered By: mousetail

You could do something like that

b = [x for x in a if x < 0] + [x for x in a if x == 0] + [x for x in a if x > 0]
Answered By: bitflip
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.