python lambda function

the definition of lambda function

  • new literal defining usual functions by one line
  • usually it is used for defining one-time functions
  • after :, only expression can follow
  • lambda function is An object too
1
2
f = lambda x: x + 1
print f(1)
  1. Assigning variables and calling the lambda function having two parameters

    1
    2
    g = lambda x,y: x + y
    print g(1,2)
  2. Defining the lambda function having default argument

    1
    2
    3
    g = lambda x, inc=1: x+inc
    print g(10) # default argument(inc=1) value is used
    print g(10, 5)
  3. Defining the lambda function having variable argument

    1
    2
    3
    #args is returned
    vargs = lambda x, *args: args
    print vars(1,2,3,4,5)

Using lambda functions

  • Using usual function

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    def f1(x):
    return x*x + 3*x - 10

    def f2(x):
    return x*x*x

    def g(func):
    return [func(x) for x in range(-10, 10)]

    print g(f1)
    print g(f2)
  • Usiung lambda function

    1
    2
    3
    4
    5
    def g(func):
    return [func(x) for x in range(-10, 10)]

    print g(lambda x: x*x + 3*x - 10)
    print g(lambda x: x*x*x)

Utilizing lambda function

  • map, filter, reduce built-in functions
  1. map built-in function

    • map(function, seq): taking item by item in seq and running function with the item and returning the result as the type of seq

      1
      2
      3
      4
      5
      def f(x):
      return x * x
      X - [1,2,3,4,5]
      Y = map(f, X)
      print Y
    • Using map and lambda function - most recommended

      1
      2
      X = [1,2,3,4,5]
      print map(lambda x: x * x, X)
  2. filter built-in function

    • taking item by item in seq and running function with the item and returning the result as the type of seq if the result is True
      1
      print filter(lambda x: x>2, [1,2,3,45])
  3. reduce built-in function

    • reduce(function, seq[,initial])
    • about each items in seq, applying function and mapping as A value
    • the 1st paremeter(function) should take two values(ex: x,y)
      1. the items of seq get into y
      2. the result after calling the function gets into x
    • optionally, the 3rd parameter initial is used as default value of x at the 1st step
      1
      2
      print reduce(lambda x, y: x + y, [1,2,3,4,5])
      print reduce(lambda x, y: x + y, [1,2,3,4,5], 1000)
Comments