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]

Leave a Comment