7

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?

2
  • I know that, but it is not the case in above example Commented Dec 12, 2011 at 18:24
  • 2
    Don't use the cmp argument. Use key. Commented Dec 12, 2011 at 18:36

3 Answers 3

21

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.

Sign up to request clarification or add additional context in comments.

Comments

8

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

Comments

2

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)

1 Comment

actually, your "<" should be a ">"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.