30

I have this list

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

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 in the result.

0

5 Answers 5

65

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

>>> lst = [1, -5, 10, 6, 3, -4, -9]
>>> sorted(lst, key=abs, reverse=True)
[10, -9, 6, -5, -4, 3, 1]
Sign up to request clarification or add additional context in comments.

Comments

17

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.

Comments

0
sorted([5, 2, 3, 1, 4])

See here for more details.

1 Comment

Try to run this with the given input list, and check whether the result really matches the expected one
0

If you want to keep the sign but sort by absolute value, you can use the key parameter in the sorted function like this:

sorted([1,-5,10,6,3,-4,-9], key=lambda x: abs(x), reverse=True)

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

This sorts the list in descending order based on the absolute values while preserving the original signs.

You can also use the abs function directly as shown in other posts.

1 Comment

How is this different from the already existing answers? Please don't dig out posts if you don't have new insights to share.
-2

I'm providing code with output data:

example_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

example_list.sort()
print("Ascending ordered list: ", example_list)

example_list.sort(reverse=True)
print("Descending ordered list: ", example_list)

Output:

Ascending order: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
Descending order: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

2 Comments

This hardly contributes anything new relative to the older answers, and misses the crucial requirement to ignore signs.
Again, it does not cope correctly with negative numbers as required in the question; and anyway, it only repeats things which have been explained in previous answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.