Are you talking about this lambda
function?
f = lambda x: x**2 + 2*x - 5
As you said, lambda
is often useful.
Python also supports a programming style called functional programming
.
functional programming
is a programming style that passes a function to another function, such as a value.
For example,
mult3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])
stores [3, 6, 9] in mult3
. If you use Lambda,
def filterfunc(x):
return x % 3 == 0
mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9])
It has the advantage of being able to express it more simply than writing it together.
Of course, in this case, you can express it similarly in the list,
mult3 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 3 == 0]
In other cases, for example, if you can't write a list,
If you want to write the value returned from the function as a function as shown below,
The shortest way is to write lambda
.
def transform(n):
return lambda x: x + n
f = transform(3) #f is written as a function
f(4) # The result is 7
lambda
is a feature that is hard to learn at first, but is definitely useful.
© 2025 OneMinuteCode. All rights reserved.