Lambda function
Lambda functions are anonymous functions i.e. functions without names. This is because they are mostly one-liners or are only required to be used once.
Syntax:
lambda argument(s): expression
lambda keyword is used to define an anonymous function in python. Arguments are the variables that are required to evaluate the expression. Expression is the body of the function. After evaluation, the expression is returned.
The lambda function can also be stored in a variable for future use.
Traditional way
Python3
def sum (a, b): return a + b # function call sum ( 1 , 5 ) |
One Liner
Python3
def sum (a, b): return a + b |
The above lambda function returns the sum of two values passed in arguments. The function is stored in a variable named, sum
To call the function:
sum(30, 12)
We can also directly call the lambda function where it is defined:
Python3
print (( lambda a, b: a + b)( 1 , 5 )) # returns 6 |
where the first set of parenthesis contains the definition of the function and the second one contains the parameters passed.
10 Useful Python One Liners That Developers Must Know
Python is known for its easy-to-code and intuitive syntax. And one-liners are like the cherry on the cake which makes Python a more beautiful and beloved programming language. There are numerous features in Python Language and one of its most loved features is its one-liners. Writing Code in Python is already easy compared to other programming languages and using the one-liners makes it more easier and cool. Now let’s see what are these Python one-liners.
Contact Us