Day - 33 of DevOps

Day - 33 of DevOps

Python Lambda Function

The lambda function in Python is one of the most interesting topics because it allows you to write a function on a single line.

Incredibly, Python lambda can do that. Python’s lambda function provides a very elegant method for performing difficult tasks with ease.

We will go over how the lambda function works and how to use it in Python. Let’s start with the basics of our topic, "Lambda Function in Python."

What is Lambda Function in Python?

Python Lambda Functions are anonymous functions or functions without a name. A standard Python function, as we know, is defined with the def keyword.

Python uses the lambda keyword in this manner to define an anonymous function.

Syntax of Lambda Function in Python

The syntax for Python lambda is provided below.
Syntax

lambda arguments: expression
  • There is only one expression that is evaluated and returned in this function, regardless of the number of parameters.

  • Lambda functions can be used anywhere that function objects are required.

  • The fact that lambda functions are syntactically limited to a single expression must always be kept in mind.

  • In addition to several kinds of expressions in functions, it has a variety of purposes in specific programming disciplines.

The characteristics of lambda functions are:

  1. The lambda function can take many arguments but can return only one expression. Here the expression is nothing but the result returned by the lambda function.

  2. Lambda functions are syntactically restricted to return a single expression.

  3. You can use them as an anonymous function inside other functions.

  4. The lambda functions do not need a return statement, they always return a single expression.

Use lambda functions when an anonymous function is required for a short period of time. — I don’t why they say this, if you know, please let me know, I’m curious.

Python Lambda Function Example

str1 = 'gokul-python-lambda'
# lambda returns a function object
upper = lambda string: string.upper()
print(upper(str1))

Output:

GOKUL-PYTHON-LAMBDA

Explanation: In the example above, we constructed a lambda function called uppercase.

Congrats🎉, On Learning the Python Lambda.

Happy Learning :)