Creepy Ways to Invoke a Function in Python: Lambda
A big data expert explores one of the more powerful, and fun, facets of Python, lamba functions, and how they can be used in data science.
Join the DZone community and get the full member experience.Join For Free
Whenever I begin learning a new language, I immediately get super cocky and say out loud, “I know everything, I’m a genius how hard can it be!?”
... before those beastly bus terminal cops come and ask me to leave.
But, as always, while snoozing under the bridge covered in my own soil, I perk up and realize that this particular language has handed me a challenge.
Python has a couple of very sexy ways of invoking a function.
Even the name is sexy, isn't it? Python.
I never digress.
Sure you can just define a function...
def hello(first_name, last_name): print("Hello World "+first_name+last_name) return
Then call it...
But that's is so 90's.
"Hey nerd, did that function come with a free Beanie Baby?"
And, yeah, I know Python was invented in the '50s to defeat Hitler's Spanish Armada, but sometimes old things can still seem new.
Upon first exploring the lambda operator my brain contracted and shat out the word “No” several times.
(Shat is not a curse word.)
The lambda operator is a quick and useful way of declaring, using, and throwing away a small function...
The general expression of a lambda function is this...
lambda argument_list: expression
The lambda operator is useful when you just want a simple calculation done on a set of data ONCE. You don’t have to name it and you can use it with other operators like Map or Filter which makes it an extremely powerful tool...
myList = [0,1,2,3,4,5,6,7] result = map(lambda x: x * 2, myList)
The above code block will apply the map operator to your little lambda function, multiplying everything in your list by 2.
Some developers don't use this technique, mainly for readability reasons. Some will claim that it is more difficult to study code like this then code with obviously declared functions.
On the other hand, many will contest that the lambda function is MORE readable and constructive than its generic counterpart. In my opinion, it comes down to a situational question.
A lambda call could theoretically stretch out to hundreds or even thousands of characters. I'm not sure you're going to find anyone claiming that this makes code easier to follow. Quite to the contrary, and probably a good spot to construct a function in its original intended shape (or an entire Class, but let's not get into that just yet).
However you end up using it, lambda can be a fantastic, fast (and fun) alternative.
Opinions expressed by DZone contributors are their own.