# This is a normal function:
def Function(Parameter):
return Parameter
# And this is a lambda function
Function = lambda Parameter : Parameter
"""
They are both equivalent and do the exact same job (which is
to take in a parameter and output it, in this scenario) the reason
lambda functions exist is to make code shorter and readable since
a lambda function only takes up one line.
Lambda functions are mostly used for simple things
Whereas defining functions are used for complex things.
You do not have to use lambda functions, it's all about preference.
An example of where it would be used is in basic arithmetics, im only
going to show addition, I think you can work out the rest:
"""
Add = lambda a, b: a + b
print(Add(3,4))
# Output:
# >>> 7
# Its equivalent:
def Add(a ,b):
return a + b
print(Add(3,4))
# Output:
# >>> 7
Lamda is just one line anonymous function
Useful when writing function inside function
it can take multiple arguments but computes only one expression
Syntax:
x = lambda arguments : expression
A lambda expression is a short block
of code which takes in parameters
and returns a value. Lambda expressions
are similar to methods, but they do
not need a name and they can be
implemented right in the body of a method.
parameter -> expression
To use more than one parameter, wrap them in parentheses:
(parameter1, parameter2) -> expression
Example
Use a lamba expression in the ArrayList's
forEach() method to print every item in the list:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}
Lamda is just one line anonymous function
Useful when writing function inside function
it can take multiple arguments but computes only one expression
Syntax:
x = lambda arguments : expression
# The lambda keyword in Python provides a
# shortcut for declaring small and
# anonymous functions:
add = lambda x, y: x + y
print(add(5, 3))
# Output
# 8
# You could declare the same add()
# function with the def keyword:
def add(x, y):
return x + y
print(add(5, 3))
# Output
# 8
# So what's the big fuss about?
# Lambdas are *function expressions*:
print((lambda x, y: x + y)(5, 3))
# Output
# 8
# • Lambda functions are single-expression
# functions that are not necessarily bound
# to a name (they can be anonymous).
# • Lambda functions can't use regular
# Python statements and always include an
# implicit `return` statement.