lambda syntax code example

Example 1: python anonymous function

# You have to save the lambda expresion for it to work

nameOfLambda = lambda arg1, arg2: expression

Example 2: lambda condition python

f = lambda parameter : exp1 if cond else exp2

# example
f = lambda x: "even" if x%2==0 else "odd"

Example 3: lambda python

add = lambda a, b : a + b
add(3,6) ## 9

Example 4: lambda python

even = lambda a: True if a % 2 == 0 else False
even(6) ## True
even(9) ## False

Example 5: lambda expressions

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); } );
  }
}

Example 6: lambda python

def sumn(n):
  return lambda a: a + n
sum5 = sumn(5)
sum5(3) ## 8