Coventry University Logo
4061CEM - Programming and Algorithms 1

Lambda Functions

Dr Ian Cornelius

Hello

  • Learning Objectives
    1. Understand what a lambda function is
    2. Demonstrate the ability to use lambda functions

What is a Lambda?

  • A function that is small and anonymous
  • They can take any number of arguments, but only a single expression
lambda arguments: expression

Lambda Example (1)

  • Add 10 to a variable and return the result
x = lambda a: a + 10
x(5)

15

Lambda Example (2)

  • Multiply variable a with b and return the result
x = lambda a, b: a * b
x(5, 10)

50

Lambda Example (3)

  • Sum the variables a, b and c and return the result
x = lambda a, b, c: a + b + c
x(5, 10, 15)

30

Why use Lambda? (1)

  • Useful when they are used as an anonymous function that is within another function
    • i.e. a function definition takes one argument, and the argument will be divided by an unknown number
def my_function(n):
    return lambda a: a / n
  • We can use the function above to always halve the number that you send to it
half_number = my_function(2)

half_number(10) = 5.0

half_number(15) = 7.5

half_number(20) = 10.0

Why use Lambda? (2)

  • The same `my_function’ can be used to calculate a division by 3
def my_function(n):
    return lambda a: a / n
third_number = my_function(3)

third_number(3) = 1.0

third_number(6) = 2.0

third_number(9) = 3.0

Why use Lambda? (3)

  • The function can then be used simultaneously to divide by 2 and 3
def my_function(n):
    return lambda a: a / n
half_number = my_function(2)
third_number = my_function(3)

half_number(10) = 5.0

third_number(3) = 1.0

third_number(6) = 2.0

Goodbye

  • Questions?
    • Post them in the Community Page on Aula
  • Contact Details: