Python Forum

Full Version: Help with Sorting
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to understand how to sort an array in Python 3.x using the bulit in sort function. So I wrote the following code. However, it did does not work.

    a = [1,-2,3,-4,5,-6]
    sorted(a, cmp = numeric_compare ) 
where numeric_compare is defined as follows:
def numeric_compare(x, y):
    return abs(x) - abs(y)
What I want to do is sort the array by the absolute values of the numbers. I realize, in this case the array is already sorted in that order.

Bob
you need to understand the difference between sorted() function and sort() method, e.g. list.sort() method

sorted() built-in function takes iterable and will return it sorted, i.e. you need to assign what it returns to a variable in order to use it later. it can be the same, e.g.
>>> a = [3, 1, 4, 2]
>>> a = sorted(a)
>>> a
[1, 2, 3, 4]
one possible use is to itreate over sorted iterable, without changing the original one
>>> a = [3, 4, 1, 2]
>>> for item in sorted(a):
...    print(item)
... 
1
2
3
4
>>> a
[3, 4, 1, 2]
while sort() method will sort the iterable in place, e.g.
>>> a = [3, 1, 4, 2]
>>> a.sort()
>>> a
[1, 2, 3, 4]
Thank you for the response. However, your code sorts based upon the number, not the absolute value of the number. Is there a way for me to pass a comparison function to the sort (or sorted) in Python?

Thanks,
Bob
You can with specifying the key argument:

import math

a = [0, 1, -3, -5, 6, 21, -34, 43, -45, 65, -68]
sorted(a, key=math.fabs)
Output:
[0, 1, -3, -5, 6, 21, -34, 43, -45, 65, -68]
There is also reverse=True option if you want to change the order.
>>> a = [-2, -1, 0, 1, 2]
>>> a.sort(key=abs)
>>> a
[0, -1, 1, -2, 2]
j.crater and buran,

Thanks for the response. Your solution works and you taught me something but is there a way to specify the comparison function that sort function uses. For example, if I wanted all prime numbers to come out a head of all composite numbers, is there a way to do that? Is the solution to write my own sort function?

Thanks,
Bob