Reputation: 1
def createmultipier(x):
return lambda y: y*x
multiply= createmultipier(10)
print(multiply(15))
Here multiply
is a variable then how did he put value to it and how did that work?
Upvotes: 0
Views: 53
Reputation: 71542
createmultiplier(10)
creates a function that multiplies its argument by 10. That's what multiply
is assigned to -- hence multiply(15)
returns 150
.
To put it another way:
multiply = createmultiplier(10)
has the same effect as doing:
def multiply(y)
return 10 * y
The point of a function like createmultiplier
is to let you create functions without a def
statement and without having to hard-code implementation details like the constant 10
. For example, if you wanted multipliers for all numbers from 1 to 4, you could do:
def times_1(y):
return 1 * y
def times_2(y):
return 2 * y
def times_3(y):
return 3 * y
def times_4(y):
return 4 * y
multipliers = [times_1, times_2, times_3, times_4]
print([m(10) for m in multipliers]) # [10, 20, 30, 40]
but it's much easier to do:
def create_multiplier(x):
return lambda y: y*x
multipliers = [create_multiplier(x) for x in range(1, 5)]
print([m(10) for m in multipliers]) # [10, 20, 30, 40]
Upvotes: 2