Lambda Function in Multiple Lines in Python

Lambda Function in Multiple Lines in Python

  1. the lambda Function in Python
  2. the lambda Function in Multiple Lines in Python

We will introduce the lambda function in python and how to use it in multiple lines in our applications in python.

the lambda Function in Python

We normally use the def keyword to define our functions in python, but python provides an anonymous function known as the lambda function. This function has no name.

The Lambda function is a small and restricted function written in one line. The Lambda function can have multiple arguments, just like a normal function with one expression.

In python, we use the lambda function to construct anonymous functions. An anonymous function consists of three main parts.

  1. The lambda keyword.
  2. Parameters.
  3. Function body.

We can use any number of parameters in a lambda function, but the body must contain only one expression. A lambda function is written in one line, which can be called immediately.

The syntax of the lambda function is as shown below.

# python
lambda x, y: x + y

The syntax shows that x and y are parameters, and x + y is an expression in a lambda function. Now, let’s discuss how we can call it immediately.

Code:

addVar = lambda x, y: x + y
print(addVar(2,3))

Output:

lambda function in python example result

the lambda Function in Multiple Lines in Python

The lambda function can only be written in one line of code, it can surely have multiple variables, but the lambda function consists of only one expression.

If you are looking for writing a function that can be written in multiple lines, you can use the def keyword instead of lambda.

Let’s go through an example in which we will create a new function that consists of multiple lines, as shown below.

Code:

def checkVal(x):
    if x < 5:
        print("X is smaller than 5")
    if x > 5:
        print("X is greater than 5")
checkVal(4)

Output:

def function in python example result

From the above code example, if we want a function that can be written in one expression, we can use the lambda function but if we need to write a function in multiple expressions and lines need to use def instead of lambda.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn

Related Article - Python Lambda

  • Python Lambda Closure
  • Use Await in a Python Lambda
  • Multiline Lambda Function in Python
  • Why There Can't Be a Multiline Lambda in Python
  • The filter() Method and Lambda Functions in Python