scdmb
scdmb

Reputation: 15621

Lambda function in sorting function

There is this code:

lista = [3,4,5,2,1,6,8,3]
print lista # [3, 4, 5, 2, 1, 6, 8, 3]
lista.sort(cmp=lambda x,y: cmp(y,x)) # sort descending
print lista # [8, 6, 5, 4, 3, 3, 2, 1] -- it is sorted

lista = [3,4,5,2,1,6,8,3]
print lista # [3, 4, 5, 2, 1, 6, 8, 3]
lista.sort(cmp=lambda x,y: y > x) # sort descending
print lista # [3, 4, 5, 2, 1, 6, 8, 3] -- nothing happens

Why does the lambda function in the second block not sort the numbers?

Upvotes: 7

Views: 12336

Answers (3)

Gevious
Gevious

Reputation: 3252

x < y returns True or False, while cmp returns 1 and -1. This code works:

lista.sort(cmp=lambda x,y: 1 if x<y else -1)

Upvotes: 2

Andrew Clark
Andrew Clark

Reputation: 208455

A cmp function needs to return a negative or positive number to indicate which element should go first (unless they are equal, then return 0). Your cmp function of y > x will only return 0 or 1. Try changing it to the following:

lista.sort(cmp=lambda x,y: (y > x) - (y < x))

I took this from the Python 3 docs:

If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).

Upvotes: 8

NPE
NPE

Reputation: 500267

The second example doesn't work because the function you're giving it isn't a valid comparator.

A valid comparator is supposed to

return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument.

The function lambda x,y: y > x doesn't fulfil this contract.

Upvotes: 21

Related Questions