Skip to content

[Python] Tutorial(9) lambda

Last Updated on 2021-04-09 by Clay

I want to share with you how to use a important feature "lambda" today.

This is a feature that I didn't use often. After all, I am too lazy, haha.

I always feel that I can use "def" directly XD (This is not a good habit

However, my lab classmates always complain: why is Python have no "switch"?

Python can actually do it on its own! But that would be more trouble compare to C.

And the legendary way is using "lambda"! (There are a lot of teaching on the internet.)

I just want to say, lambda still has its own useful place!


lambda

So, I think, first we will review a simple function definition!

def determine(n):
    if n >= 50:
        print('%s at least greater than 50!' % n)
    else:
        print('%s at least less than 50!' % n)


This is a simple function! It lets us input a value and determine if it is greater than 50.

Suppose we enter this:

determine(23)


Output:

 23 at least less than 50! 

Otherwise, if we enter:

determine(99)


Output:

99 at least greater than 50!

And then, it is the turn of today's protagonist —— lambda !

Lambda can simplify our function, as known as "anonymous function" (I'm not sure, haha), which can be defined and then refused directly when it is needed without prior definition.

For example, the function just defined:

determine = lambda n: print('%s at least greater than 50!' % n) if n >= 50 else print('%s at least less than 50!' % n)


That's right! It's been defined, one line. (serious)

Let's take a look at just two outputs:

determine(23)


Output:

23 at least less than 50!
determine(99)


Output:

99 at least greater than 50!

How, is it really working?

Lambda assigns two variable is no problem.

sum = lambda x, y: x+y
sum(1, 3)


Output:

4

So, the above is short, although, this is our lambda tutorial. If I use it more familiar and find more applications in the future, I think I will update this article again.

Please look forward to it without expectation!


References


Read More

Leave a Reply