DEV Community

Cover image for Lambda Expressions

Posted on

Lambda Expressions

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)
>>> f(10,15)

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

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

Top comments (5)

jhelberg profile image
Joost Helberg

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.

mzaini30 profile image

It's like map in Javascript

rodiongork profile image
Rodion Gorkovenko

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

saint4eva profile image

Using fat arrow like C# would have been better.