Home » Python

lambda keyword with example in Python

Python lambda keyword: Here, we are going to learn about the lambda keyword with example.
Submitted by IncludeHelp, on April 15, 2019

Python lambda keyword

lambda is a keyword (case-sensitive) in python, it is used to create an anonymous function that can accept any number of arguments but a single expression/statement.

Syntax of lambda keyword

    function_name = lambda parameters_list : expression

Example:

    Input:
    # lambda function to find power
    power = lambda x,y : x**y

    # calling function
    result = power(10, 3)
    print(result)

    Output:
    1000

Python examples of lambda keyword

Example 1: Create a lambda function to find sum of 4 numbers.

# python code to demonstrate example of 
# lambda keyword

# Create a lambda function to find sum of 4 numbers

# lambda function to add 4 numbers
addnumbers = lambda n1,n2,n3,n4 : n1+n2+n3+n4

# numbers
a = 10
b = 20
c = 30
d = 40

# printing the sum by calling lambda function
print("sum = ", addnumbers(a,b,c,d))

Output

sum =  100

Example 2: Create a lambda function to find a to the power b, where, a and b are the parameters.

# python code to demonstrate example of 
# lambda keyword

# Create a lambda function to find a to the power b, 
# where a and b are the parameters

# lambda function to find power
power = lambda x,y : x**y

a = 10  # base
b = 3   # power

# calling function
result = power(a,b)

# printing the result
print("power of ", a, " and ", b, " is = ", result)

Output

power of  10  and  3  is =  1000


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.