Sorting by absolute value without changing to absolute value Sorting by absolute value without changing to absolute value python-3.x python-3.x

Sorting by absolute value without changing to absolute value


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]


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)))


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