Lambda Expressions in Python with Syntax and Examples


1. Objective

When creating functions in Python, we use the def keyword. We bind them to a name while doing so. But sometimes, we may want to declare a function anonymously. Or we may want to use a function only once. In such a case, defining a function seems a bit extra. In this tutorial, we look at lambda expressions in Python for such cases.

Lambda expressions in python

2. An Introduction to Lambdas

A lambda expression in Python allows us to define a function anonymously. It is worthwhile to note that it is an expression, not a statement. That is, it returns a value; it has an implicit return statement. The following is the Python syntax of a lambda expression.

lambda [arg1,arg2,..]:[expression]

Where you place the lambda expression, it returns the value of the expression.

3. Declaring Lambda expressions in python

To declare a lambda, you use the lambda keyword.

>>> lambda e:e-2
<function <lambda> at 0x03DBA978>

You can assign it to a variable if you want to be able to call it again later.

>>> downbytwo=lambda e:e-2

Here, e is the argument, and e-2 is the expression. Then you would call it like you would call any other function. Here, we passed the integer 1 as an argument.

>>> downbytwo(1)

-1

You can also pass an argument along with the declaration. Use parentheses for this.

>>> (lambda e:e-2)(1)

-1

4. What Exactly is an Expression?

As we’ve seen, the expression is what the lambda returns, so we must be curious about what qualifies as an expression. An expression here is what you would put in the return statement of a function. The following items qualify as expressions.

  1. Arithmetic operations like a+b and a**b
  2. Function calls like sum(a,b)
  3. A print statement like print(“Hello”)

Other things like an assignment statement cannot be provided as an expression to a lambda, because it does not return anything, not even None.

5. When to Use Which

Like we’ve seen so far, a lambda expression may take arguments, and takes one expression. The value of this expression is what it returns after evaluating. A lambda expression isn’t necessary, but it’s handy in certain situations. These are:

1. When you have only a single statement to execute in your function

Suppose we want to print a Hello in the body of a function printhello(). In this function’s body, we have only one line of code.

>>> def printhello():
            print("Hello")
>>> printhello()

Hello

Now, let’s do this with a lambda expression.

>>> (lambda :print("Hello"))()<strong>

Hello

Notice that we did not provide any arguments here. We’ll discuss about this in a later section in this article. Let’s take another example yet.

>>> z=lambda a=2:print("Hello")
>>> z()

Hello

2. When you need to call that code only once

One of the main reasons why we use functions, apart from modularity, is reusability of code. But when you want to need some code only once, or less often, you may use a lambda expression in place of defining a function for it.

6. Defaults in a Lambda

In Python, and in other languages like C++, we can specify default arguments. But what is that? Suppose a function func1() has an arity of 2 with parameters a and b. What happens if the user provides only one argument, or none? This is why you may want to provide default values to your parameters. Let’s take an example.

>>> def func1(a=2,b=3):
           print(a,' ',b)
>>> func1()

2   3

>>> func1(3)

3   3

Here, the default values for a and b are 2 and 3, respectively.

To call as y(), need default arguments:

>>> o=lambda x=1,y=2,z=3:x+y+z
>>> o(2,3)

8

>>> o(2)

7

>>> o
<function <lambda> at 0x00A46150>
>>> o()

6

7. A Deeper Look Into The Syntax of a Lambda

We’ve seen how we declare a lambda expression, but where there are building blocks, there are possibilities. So, let’s see what we can or can’t do with a lambda.

a. Arguments

One or more variables appearing in the expression may be declared previously. But if it’s there in the arguments, either it should have a default value or must be passed as an argument to the call.

>>> a,b=1,2
>>> y=lambda a,b:a+b
>>> y()
Traceback (most recent call last):
File "<pyshell#167>", line 1, in <module>
y()

TypeError: <lambda>() missing 2 required positional arguments: ‘a’ and ‘b’

Here, both a and b are missing values.

>>> y=lambda a:a+b
>>> y()
Traceback (most recent call last):
File "<pyshell#169>", line 1, in <module>
y()

TypeError: <lambda>() missing 1 required positional argument: ‘a’

The variable a is still missing a value.

>>> y=lambda :a+b
>>> y()

3

Finally, since no argument here is missing a value, it works just fine.

b. Omitting Arguments

It isn’t mandatory to provide arguments to a lambda expression, it works fine without them.

>>> y=lambda :2+3
>>> y()

5

Another example would be where the expression is a print statement.

>>> (lambda :print("Hi"))()

Hi

Hence, we conclude that omitting arguments is acceptable.

c. Omitting the Expression

Now let’s try if it works without an expression.

>>> y=lambda a,b:

SyntaxError: invalid syntax

Clearly, it didn’t work. And why would it? The expression’s value is what it returns, so without an expression, it would be a waste of time.

8. Lambdas with In-Built Functions

There are some built-in functions, like filter() and map(), on which we can apply a lambda expression to filter out elements from a list. Let’s see how. First, we take a list called numbers.

>>> numbers=[0,1,2,3,4,5,6,7,8,9,10]

Next, we take a lambda function as follows.

lambda x:x%3==0

a. filter()

The filter() function takes two parameters- a function, and a list to operate on. Finally, we apply the list() function on this to return a list.

>>> list(filter(lambda x:x%3==0,numbers))

[0, 3, 6, 9]

This is the final code for our purpose, and guess what it does. Well, this code takes the list ‘numbers’, and filters out all elements from it except those which do not successfully divide by 3.

Note that this does not alter the original list.

b. map()

The map() function, unlike the filter() function, returns values of the expression for each element in the list. Let’s take the same list ‘numbers’.

>>> list(map(lambda x:x%3==0,numbers))

[True, False, False, True, False, False, True, False, False, True, False]

c. reduce()

Lastly, the reduce() function takes two parameters- a function, and a list. It performs computation on sequential pairs in the list, and returns one output. But to use it, you must import it from the functools module.

>>> from functools import reduce
>>> reduce(lambda x,y:y-x,numbers)

5

Let’s perform a dry run.

1-0=0

2-1=1

3-1=2

4-2=2

5-2=3

6-3=3

7-3=4

8-4=4

9-4=5

10-5=5

Hence, it outputs 5. Let’s take another example.

>>> reduce(lambda x,y:y+x,numbers)

55

Try doing the same thing here for y+x instead; you should get 55.

9. Conclusion

That’s all for today. We learned quite a bit about lambda expressions, how to create them, and what’s proper lambda syntax. Then we saw what qualifies as an expression, and also learned how to provide default arguments. Finally, we tried out three functions, filter(), map(), and reduce(), to make use of lambdas. A lambda, as compared to a normal function, offers its own benefits. Tell us what you think.

Leave a comment

Your email address will not be published. Required fields are marked *