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(numb
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)))
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]
lst = [-1, 1, -2, 20, -30, 10]
>>>print(sorted(lst, key=abs))
>>>[-1, 1, -2, 10, 20, -30]