×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python lambda Keyword

By IncludeHelp Last updated : December 07, 2024

Description and Usage

The 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

Syntax of lambda keyword:

function_name = lambda parameters_list : expression

Sample Input/Output

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

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

Output:
1000

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 ↻


Advertisement
Advertisement
Advertisement



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