What are the advantages of lambda?

Asked 2 years ago, Updated 2 years ago, 89 views

I'm studying lambda now.

lambda is sometimes good to use, I don't feel like Python because it's hard to learn and it's not readable. The function won't change later, right?

Is lambda a function that can be used like goto statement in c, but should not be used?

python lambda

2022-09-21 15:20

1 Answers

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.


2022-09-21 15:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.