What is the lambda

Hello, everyone. Today we are going to bring you a detailed analysis of lambda expressions in Python. Lambda has many uses in Python, but to be honest, I personally think the debate about lambda is not about how to use it, but whether to use it at all. I’m going to share my learning experience with you through lots of examples, and maybe you’ll come to the same conclusion as me.

Okay, first let’s get the basic definition straight, what is lambda?

Lambda expresses special syntax in Python for creating anonymous functions. We refer to lambda syntax itself as lambda expressions, and the functions derived from it as lambda functions.

To summarize, lambda can be thought of as a small anonymous function that can take any number of arguments but only one expression. The function is expressed as follows:

  • Lambda argument: Manipulate (argument)
  • Argument: Argument is the argument passed in by the anonymous function, followed by the colon

Let’s look at the simplest example by referring to the definition template and parameters above:

Add_one = lambda x:x+1 # 1 add_nums = lambda x,y:x+y # 2 Print (add_one(2)) print(add_nums(3,7)) print(add_nums(3,7)Copy the code

Compared with lambda anonymous functions, we have found the characteristics of lambda anonymous functions, that is, for relatively simple functions, there is no need to def a single line, you can write, pass parameters and execute methods at one go

Explanation of lambda usage

Next, let’s take a look at the actual application of lambda. In my experience with lambda, I have never used lambda alone. Lambda is generally mixed with excellent built-in functions such as Map, filter and Reduce and data structures such as dict, list,tuple and set. This is how it gets the most out of itself. If you are not familiar with these built-in functions, you can take a look at my previous article on the Path to Python: Map, filter, reduce, and zip

Well, without further ado, let’s take a look at each one

lambda + map

First up is the lambda+map combination, starting with the following example:

Numbers = [1,2,3,4,5] add_one = list(map(lambda n:n+1,numbers)) print(list(add_one)) print(tuple(add_one)) Out: [2, 3, 4, 5, 6] (2, 3, 4, 5, 6)Copy the code

Map (fun,sequence). Fun is passed. Sequence is an iterable sequence. Here fun is lambda n:n+1. This perfectly explains the original design of lambda, because without lambda, our solution is as follows:

Def add (num) : return num + 1 Numbers = [1, 2, 3, 4, 5] add_one = list (map) (add, Numbers) print (add_one) print (tuple (add_one))Copy the code

Obviously, the add method here is a bit redundant, so lambda is a good alternative. Let’s take a look at the next example, which is a bit of code I wrote while backing up my own logs, and it’s not named very well:

from datetime import datetime as dt logs = ['serverLog','appLog','paymentLog'] format Format (dt.now().strftime('%d-%m-%y')) result =list(map(lambda x:x+format,logs)) # print(result) Out:['serverLog_11-02-19.py', 'appLog_11-02-19.py', 'paymentLog_11-02-19.py']Copy the code

This is pretty much the same as the + 1 example, but instead of concatenating strings, lambda isn’t a very good solution. Finally we’ll say, now that you have a feel for map + lambda, let’s have another example of interacting with dict dictionaries:

person =[{'name':'Lilei', 'city':'beijing'}, {'name':'HanMeiMei', Name =list(map(lambda x:x['name'],person) print(names) Out: ['Lilei', 'HanMeiMei']Copy the code

Ok, so it’s pretty clear how map+lambda is used here

lambda + filter

The combination of lambda and filter is also common for certain filters, and it should make sense now to look at the filter example from the previous article:

Numbers = [0, 1, 2, -3, 5, -8, 13] Print ("Odd numbers are :",list(result)) # X % 2 == 0, numbers) print("Even numbers are :",list(result)) X >0, numbers) print("Positive numbers are :",list(result)) Out: Odd numbers are: [1, -3, 5, 13] [0, 2, -8] Positive Numbers are : [1, 2, 5, 13]Copy the code

The function of the lambda (x%2,x%2==0,x>0) can return True or False, which meets fiter’s requirements. Using the examples of Li Lei and Han Meimei, this is also the case:

person =[{'name':'Lilei', 'city':'beijing'}, {'name':'HanMeiMei', 'city':' Shanghai '}] names=list(filter(lambda x:x['name']=='Lilei',person) 'Lilei', 'city': 'beijing'}]Copy the code

lambda + reduce

Again, let’s look at the example from the previous post:

From functools import reduce # Only Python 3 numbers = [1,2,3,4] result_multiply = reduce((lambda x, y: X * y), numbers) result_add = reduce((lambda x,y: x+y), numbers) print(result_multiply) Print (result_add) Out: 24 10Copy the code

This example uses lambda and reduce to implement list accumulative sums and accumulative multiplications. What’s interesting is that this example has two sides. It shows how lambda and Reduce can be used together, but it also brings me to my next point: is Lambda really worth using? How exactly should it be used?

Avoid excessive use of lambdas

You have seen lambda in action through the examples above, but I would like to share with you my opinion: I think the disadvantages of lambda are slightly more than the advantages, and excessive use of lambda should be avoided

First of all, this is just my personal opinion, I hope you understand why I say so, first of all, let’s take lambda method and regular DEF contrast, I find lambda and DEF main differences are as follows:

  • Can be passed immediately (no variables required)
  • One line of code, concise (not necessarily efficient)
  • It can return automatically without a return
  • Lambda functions do not have function names

We can see its advantages, but I want to talk about its disadvantages. First of all, from the real needs, we do not need lambda most of the time, because we can always find a better alternative. Now let’s take a look at the example of lambda+ Reduce, and the results we achieved with Lambada are as follows:

From functools import reduce # Only Python 3 numbers = [1,2,3,4] result_multiply = reduce((lambda x, y: x * y), numbers) result_add = reduce((lambda x,y: x+y), numbers)Copy the code

Lambda is not a simple and efficient way to do this, because we have the sum and MUL methods ready to use:

From functools import reduce from operator import mul numbers = [1,2,3,4] result_add = sum(numbers) result_multiply =reduce(mul,numbers) print(result_add) print(result_multiply) Out: 10 24Copy the code

The results are the same, but the sum and MUL schemes are obviously more efficient. As another common example, suppose we have a list of colors and now require each color to start with a capital letter. Lambda would look like this:

Colors = ['red','purple','green','blue'] result = map(lambda c:c.capitalize(),colors) print(list(result)) Out: ['Red', 'Purple', 'Green', 'Blue']Copy the code

It sounds nice and neat, but we have a better way:

Colors = ['red','purple','green','blue'] result = [c.capitalize() for c in colors] print(result) Out: ['Red', 'Purple', 'Green', 'Blue']Copy the code

3. Sorted: sorted: sorted: sorted: sorted

colors = ['Red','purple','Green','blue']
print(sorted(colors,key=str.capitalize))

Out:['blue', 'Green', 'purple', 'Red']
Copy the code

Another major reason is that lambda functions do not have function names. So there’s a lot of difficulty for the team in code handiwork, project migration scenarios. It doesn’t hurt to write an extra function add_one(), because it’s easy for everyone to understand and know that it does +1, but if you use a lot of lambdas in your module on the team, it’s going to cause a lot of trouble for everyone else to understand

Suitable for lambda scenarios

Then again, existence is reason, so what are the scenarios where we really need lambda:

  1. The methods you need are simple (+1, string concatenation, etc.) and the function doesn’t deserve a name
  2. Lambda expressions are easier to understand than function names we might think of
  3. Other than lambda, there are no functions provided by Python that can do this
  4. All members of the team have lambda, and you’re allowed to use it

Another scenario that works well is to give the impression that you are a professional, as in:

Hey, buddy, I heard you learned Python. Do you know lambda? Haven’t heard? No, it’s no use learning! Come on, let me tell you about… Ten thousand words are omitted here

conclusion

Today I’ve gone over the usage and scenarios of lambda, which is used to create simple anonymous functions 90% of the time, and slightly more complex functions 10% of the time (I’m making a really good excuse).

The bottom line is that everything has two sides, and we should pause before using lambda and ask ourselves if we really need it.

Of course, if you need to talk with others all the time, lambda is good or bad depends on how we say it, please follow the following principles when bragging, it is always successful:

If you say that a female college student prostituting herself at night is shameful, but if you change it to a prostitute who studies hard in her spare time, it is much more inspiring!

Lambda is the same thing