28

I have this list

[1,-5,10,6,3,-4,-9]

But now I want the list to be sorted like this:

[10,-9,6,-5,-4,3,1]

As you can see I want to order from high to low no matter what sign each number has, but keeping the sign, is it clear?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504

3 Answers3

59

Use abs as key to the sorted function or list.sort:

>>> lis = [1,-5,10,6,3,-4,-9]
>>> sorted(lis, key=abs, reverse=True)
[10, -9, 6, -5, -4, 3, 1]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
16

Use:

    l.sort(key= abs, reverse = True)

Lists can be sorted using the sort() method. And the sort method has a parameter, called key, which you can pass a function. Using this parameter, your list won't be ordered by the values of the list, but by the values of your function on the list.

In your case, you should use the abs() function, which will return the absolute value of your list elements. So, your list

>>> l = [1,-5,10,6,3,-4,-9]

Will be sorted like it was

>>>  [abs(1),abs(-5),abs(10),abs(6),abs(3),abs(-4),abs(-9)]

Which should be:

>>> [1 ,-4 ,-5 ,6 ,-9 ,10]

To order from the biggest to the smalles, use the reverse=True parameter also.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Lucas Ribeiro
  • 6,132
  • 2
  • 25
  • 28
2
sorted([5, 2, 3, 1, 4])

See here for more details.

Jacob Lee
  • 4,405
  • 2
  • 16
  • 37