Nick Kremer
Nick Kremer

Reputation: 223

Sorting by absolute value without changing to absolute value

I want to sort a tuple using abs() without actually changing the elements of the tuple to positive values.

def sorting(numbers_array):
    return sorted(numbers_array, key = abs(numbers_array))


sorting((-20, -5, 10, 15))

According to the python wiki (https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions), the sorted(list, key=) function is suppose to sort with the parameter key without actually altering the elements of the list. However, abs() only takes int() and I haven't worked out a way to make that tuple into an int, if that's what I need to do.

Upvotes: 19

Views: 33543

Answers (3)

ProgrammingIsAwsome
ProgrammingIsAwsome

Reputation: 1129

So if you want to sort these 4 values (-20, -5, 10, 15) the desired output would be: [-5, 10, 15, -20], because you are taking the absolute value.

So here is the solution:

def sorting(numbers_array):
    return sorted(numbers_array, key = abs)


print(sorting((-20, -5, 10, 15)))

Upvotes: 2

user2707389
user2707389

Reputation: 827

lst = [-1, 1, -2, 20, -30, 10]
>>>print(sorted(lst, key=abs))
>>>[-1, 1, -2, 10, 20, -30]

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122382

You need to give key a callable, a function or similar to call; it'll be called for each element in the sequence being sorted. abs can be that callable:

sorted(numbers_array, key=abs)

You instead passed in the result of the abs() call, which indeed doesn't work with a whole list.

Demo:

>>> def sorting(numbers_array):
...     return sorted(numbers_array, key=abs)
... 
>>> sorting((-20, -5, 10, 15))
[-5, 10, 15, -20]

Upvotes: 27

Related Questions