Python Lambda Functions

A lambda function is a function without a name i.e. an anonymous function. The keyword lambda is used to define a lambda function in Python and has only a single expression.

Syntax of Lambda Functions

lambda arguments: expressions

The lambda function can have any number of arguments, but only one expression.

Examples of Lambda Functions

The following are some of the examples of the usage of Lambda Functions:

Example 1 – Multiplying a number to an argument with Python Lambda

Demo80.py

val = lambda i: i *2
print("Result = ",val(25))

Output

Result = 50

Example 2 – Display a string with Python Lambda Functions

In this example, we will declare a string and display it with Lambda Functions.

Demo81.py

# declaring a string
str ="Hello World!!!"

# displaying using lambda functions 
(lambda str : print(str))(str)

Output

Hello World!!!

Example 3 – Lambda Functions with more than argument

In this example, we will multiply 3 arguments with lambda functions.

Demo82.py

# Multiplying 3 arguments with lambda
val = lambda i, j, k : i * j * k

# Display multiplication result of 3 arguments
print("Result = ",val(10, 20, 30))

Output

Result =  6000

Example 4 – Find the maximum of two numbers with Lambda Functions

In this example, we will use the if-else statement to display the maximum of two given numbers.

Demo83.py

# finding the maximum number
res = lambda i, j : i if(i > j) else j
 
# displaying the result
print("Maximum = ",res(50, 100))

Output

Maximum =  100

Example 5 – Find the square of a number with Python Lambda Functions

Demo84.py

# find square of a number
val = lambda i: i*i

# display the result
print("Result (square) = ",val(9))

Output

Result (square) =  81

Python Tutorial (English)

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Read More

Python File Handling
Python - Get User Input
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment