Python Lambda Function | squares the value Examples

Python lambda is the anonymous function without a name. Where normal functions are defined using def define any function in Python. Another side anonymous (unnamed) functions are defined using the lambda keyword. The advantage of it’s allowed you to write very short or small code and can’t contain any statements in a function.

Python Lambda Function | Examples

Don’t be confused with anonymous functions or lambda functions both are the same in python.

Syntax

lambda arguments : expression

Here you can use any number of arguments but only one expression in Python Lambda functions. The expression is evaluated and returns the result.

Python lambda example

The example of a lambda function that squares the value. it’s a very simple look at this.

# This Program shows the use of lambda functions

sq = lambda x: x * x

print(sq(5))

Output: 25

Multiplies Example: Python Lambdas functions Multiplies 2 argument 

multi = lambda a, b: a * b
print(multi(5, 6))

Output: 30

Sum Example: Python Lambdas functions sum 2 argument 

sum = lambda a, b: a + b
print(sum(5, 6))

Output: 11

Lambda a variable that needs to be present, Underscore _ is a valid identifier and is used here as a variable name. It will always return Truefor the argument passed to the function. The _ is variable name.

Python lambda – no arguments

Note: it can be an interview question.

lamfunc = lambda _: True

print(' missing 1 argument: ', lamfunc('?'))

Output:  missing 1 argument: True

Q: Why are Python lambdas useful? 

Answer: Python Lambdas functions are very much linked to functional programming style in general. Implementation of it can solve problems by applying a function to some data, merging the results, filter and manipulate, is what Google uses to implement most of its algorithms.

You can follow this tutorial where we used Lambdas function with a map python function – Multiple arguments into a map function using Lambdas function

Q: Why lambda function in python can’t use the “return” statement?

Answer: Because the return is a statement and the Lambdas function can only contain expressions, no statements.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Examples Python lambda is in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.