loading...
Cover image for Lambda Expressions

Lambda Expressions

bluepaperbirds profile image bluepaperbirds ・1 min read

You can create small anonymous functions in Python using the lambda keyword.

By anonymous I mean it doesn't need to have a name, normal functions start with the def keyword and require a name.A lambda expression is not a statement, it returns a value.

Lets say you want a function that returns the sum of its two arguments
Imagine you have a simple function like this:


def sum(a,b):
    return a+b

That is quite a lot to write.

Lambda expressions

Instead you can create a lambda expression like the example below.
A lambda function that adds two variables as an argument and prints the result:

lambda a, b: a+b

You can then use it like this:

>>> f = lambda a,b : a+b
>>> f(2,3)
5
>>> f(10,15)
25
>>> 

You can create all kinds of lambda expressions, this is a lot shorter to write than creating functions for tiny operations.


# A lambda function that adds 10 to the argument
x = lambda a : a + 10
print(x(8))

# A lambda function that multiplies two variables
x = lambda a, b : a * b
print(x(8, 9))

# A lambda function that sums its arguments
x = lambda a, b, c : a + b + c
print(x(1, 2, 3))

Discussion

pic
Editor guide
 

The above example makes the programmer jump abstraction levels making the code harder to read and harder to maintain.
There are reasons for using anonymous functions, but the example is not on of them.

 

If you are using a linter (ex. pycodestyle, flake8) and/or following the PEP8 coding style recommendations, you will get a warning when assigning a lambda expression into a variable.

From python.org/dev/peps/pep-0008/#prog...

Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.

Yes:

def f(x): return 2*x

No:

f = lambda x: 2*x

The first form means that the name of the resulting function object is specifically 'f' instead of the generic ''. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)

I think assigning it into a variable (say f) just makes it less clear what f is or does. Using map and passing in a lambda expression would be clearer.

Related:

 

It's like map in Javascript

 

not exactly, Javascript has dedicated syntax for anonymous functions, e.g.

    x => x+10
    // or in old-style
    function(x) { return x + 10 }

while map is just one of possible use-cases for them

 

Using fat arrow like C# would have been better.