21 Feb 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
1 2 3 |
lambda arguments: expressions |
The lambda function can have any number of arguments, but only one expression.
Examples of Lambda Functions
Following are some of the examples of the usage of Lambda Functions:
Example 1 – Multiplying a number to an argument with Python Lambda
1 2 3 4 |
val = lambda i: i *2 print("Result = ",val(25)) |
Output
1 2 3 |
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.
1 2 3 4 5 6 7 |
# declaring a string str ="Hello World!!!" # displaying using lambda functions (lambda str : print(str))(str) |
Output
1 2 3 |
Hello World!!! |
Example 3 – Lambda Functions with more than arguments
In this example, we will multiply 3 arguments with lambda functions.
1 2 3 4 5 6 7 |
# 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
1 2 3 |
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.
1 2 3 4 5 6 7 |
# finding the maximum number res = lambda i, j : i if(i > j) else j # displaying the result print("Maximum = ",res(50, 100)) |
Output
1 2 3 |
Maximum = 100 |
Example 5 – Find the square of a number with Python Lambda Functions
1 2 3 4 5 6 7 |
# find square of a number val = lambda i: i*i # display the result print("Result (square) = ",val(9)) |
Output
1 2 3 |
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
No Comments