DEV Community

\144\150\162\165\166(dhruv)
\144\150\162\165\166(dhruv)

Posted on • Edited on

2 1

Lambda Function(Python)

In Python, a lambda function is a small anonymous function without a name. It is defined using the lambda keyword and has the following syntax:

lambda arguments: expression
Enter fullscreen mode Exit fullscreen mode

Lambda functions are often used in situations where a small function is required for a short period of time. They are commonly used as arguments to higher-order functions, such as map, filter, and reduce.

Function to double the input

def double(x):
  return x * 4
Enter fullscreen mode Exit fullscreen mode

Lambda function to double the input

lambda x: x * x * x * x
Enter fullscreen mode Exit fullscreen mode

The above lambda function has the same functionality as the double function defined earlier. However, the lambda function is anonymous, as it does not have a name.

Lambda functions can have multiple arguments, just like regular functions. Here is an example of a lambda function with multiple arguments:

Function to calculate the product of two numbers

def multiply(x, y):
    return x * y
Enter fullscreen mode Exit fullscreen mode

Lambda function to calculate the product of two numbers

lambda x, y: x * y
Enter fullscreen mode Exit fullscreen mode

Lambda functions can also include multiple statements, but they are limited to a single expression. For example:

Lambda function to calculate the product of two numbers, with additional print statement

lambda x, y: print(f'{x} * {y} = {x * y}')
Enter fullscreen mode Exit fullscreen mode

In the above example, the lambda function includes a print statement, but it is still limited to a single expression.

Lambda functions are often used in conjunction with higher-order functions, such as map, filter, and reduce which we will look into later.

If you have any feedback, then you can DM me on Twitter or Linkedin.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more