Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda function in sorting function

Tags:

python

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?

like image 328
scdmb Avatar asked Dec 12 '11 18:12

scdmb


People also ask

What is lambda function with example?

Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression).

How do you create a sort function in Python?

The syntax of the sort() method is: list. sort(key=..., reverse=...) Alternatively, you can also use Python's built-in sorted() function for the same purpose.

What is lambda function and state its use?

Lambda is well-suited for Task states, because Lambda functions are serverless and easy to write. You can write code in the AWS Management Console or your favorite editor. AWS handles the details of providing a computing environment for your function and running it.

What is key lambda?

In Python, lambda is a keyword used to define anonymous functions(functions with no name) and that's why they are known as lambda functions. Basically it is used for defining anonymous functions that can/can't take argument(s) and returns value of data/expression.


2 Answers

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.

like image 198
NPE Avatar answered Nov 03 '22 01:11

NPE


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

like image 36
Andrew Clark Avatar answered Nov 03 '22 01:11

Andrew Clark