Lambda Expression Python | Function

Using Lambda Expression you can create an Anonymous Function in Python. Normal Python functions are created by using the def keyword. But when you want to declare a function anonymously use Python Lambda Expression.

The expression is executed and the result is returned:

lambda arguments : expression

Example Lambda Expression Python

Lambda functions are anonymous or nameless (a function without a name).

You use these functions when:

  • To perform a simple operation and,
  • Use this function just once.

Simple example code:

Single argument adds, and return the result:

res = lambda a: a + 10

print(res(10))

Output:

Lambda Expression Python

Lambda functions with Multiple arguments

res = lambda a, b: a * b

print(res(5, 7))

Output: 35

Python Lambda Function with List Comprehension

res = [lambda x=x: x * 10 for x in range(1, 11)]

for table in res:
    print(table(), end=', ')

Output:

10, 20, 30, 40, 50, 60, 70, 80, 90, 100,

Do comment if you have any doubts and suggestions no this Pytho lambda tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe 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.