Python Lambda Expression – Declaring Lambda Expression & Its Defaults

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

In this Python Tutorial we will study, What is Python Lambda Expression with its syntax and examples.

Moreover, we will study how to and when to declare Lambda Expression in Python, Python Lambda with inbuilt Python lambda functions, and some python functions are: reduce(), map(), and filter().

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.

So, let’s start learning Python Lambda Expression Tutorial.

Python Lambda Expression

Python Lambda Expression

What is Python Lambda Expression?

Python lambda expression 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 in Python.

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

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

How to Declare Python Lambda Expression?

To declare a lambda expression in Python, you use the lambda keyword.

>>> lambda e:e-2

Output

<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 Python Lambda function.

Here, we passed the integer 1 as an argument.

>>> downbytwo(1)

Output

-1

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

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

Output

-1

What Exactly is an Expression in Python?

As we’ve seen, the expression is what the Python3 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 Python Lambda 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 Python lambda because it does not return anything, not even None.

When to Use Which Lambda Expression in Python?

Like we’ve seen so far, Python lambda expression may take arguments, and takes one expression. The value of this expression is what it returns after evaluating.

Python 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 Python Lambda 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()

Output

Hello

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

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

Output

Hello

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

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

Output

Hello

2. When you need to call that code only once

One of the main reasons why we use functions, apart from modularity, is the reusability of code.

But when you want to need some code only once, or less often, you may use a Python lambda expression in place of defining a function for it.

Defaults in Python Lambda Expression

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 for your parameters.

Let’s take an example.

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

Output

2   3

>>> func1(3)

Output

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)

Output

8

>>> o(2)

Output

7

>>> o

Output

<function <lambda> at 0x00A46150>

>>> o()

Output

6

Python Lambda Expression Syntax

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

1. Python 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()

Output

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

Output

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

Output

3

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

2. Omitting Arguments

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

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

Output

5

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

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

Output

Hi

Hence, we conclude that omitting arguments is acceptable.

3. Omitting the Expression

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

>>> y=lambda a,b:

Output

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.

Python Lambdas with In-Built Functions

There are some built-in functions, like filter() and map(), on which we can apply Python 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

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

Output

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

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

Output

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

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

Output

5

Let’s perform a dry run.
1-0=1
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)

Output

55

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

So, this was all about Python lambda expression. Hope you like our expression.

Python Interview Questions on Lambda Expression

  1. What is Lambda Expression in Python?
  2. How to write Lambda Expression in Python?
  3. What is the advantage of Lambda Expression in Python?
  4. Explain Lambda keyword in Python?
  5. What is the syntax of Lambda function in Python?

Conclusion

That’s all for today. We learned quite a bit about Python3 lambda expression with syntax, how to create Lambda expressions in python.

Then we saw what qualifies as an expression, and also learned how to provide default arguments in Python Lambda expression.

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.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

7 Responses

  1. Maziar says:

    reduce () dry run : If I am not wrong the answer of 1-0 is 1 not 0 .

    • DataFlair Team says:

      Hello, Maziar

      Thanks for the correcting us. You’re correct; that was a typo from our end, and we have corrected it. Hope, you liked our Python Lambda Expression, we have 100+ tutorials for Python, please include them in your list.

      Thank you for making DataFlair better!

  2. PK says:

    Could you please explain more on reduce function – where it is used in real world?

    • DataFlair Team says:

      Hi PK
      reduce() is a function in the functools module. With this, you can apply a function of two arguments cumulatively to a sequence. The point here is to operate on the values and reduce it all to a single value.

      Some use cases can be to flatten a list and to turn a list of numbers into an actual number. You can use it to find the least common multiple for a number, to find the intersection to two given lists, for function composition, and for sorting operations.
      Hope, it helps!

  3. kannan says:

    Is it Lambda function or expression? Everyone says it as Lambda function? whats the difference in saying? Which one is correct?

  4. Sham Patil says:

    thank you

Leave a Reply

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