Menu
Coddy logo textTech

Returned from function

Lesson 4 of 9 in Coddy's Python Lambda Functions course.

Another interesting use case of lambda function is returning it from a function.

For example,

def power_of(a):
	return lambda b : b ** a

cube = power_of(3)  # holds lambda b : b ** 3
square = power_of(2)  # holds lambda b : b ** 2
square_root = power_of(0.5)  # holds lambda b : b ** 0.5

print(cube(4))  # prints 64
print(square(4))  # prints 16
print(square_root(4))  # prints 2

As you see it's a way to generate multiple small functions.

It's also possible to create a lambda which returns lambda (when it's one expression),

power_of = lambda a : lambda b : b ** a

print(power_of(2)(5))  # prints 25 = 5 ** 2
challenge icon

Challenge

Easy

Create a function named message_constructor that gets two strings: first name and last name. Last name can be None.

The function will construct a name out of the two arguments, with the following conditions:

  • If only the first name exists, then the name will be equal to the first name
  • If both of the arguments exist then the function will combine them with a space in between.

The function will return a lambda function that will get one argument, and will return a string.

Take a look at the test cases to understand the needed format from the lambda.

Try it yourself

def message_constructor(first, last):
    # Write code here

All lessons in Python Lambda Functions

1Lambdas

IntroductionSyntaxWith argumentsReturned from function

2With built-in Function

filtermap