Creepy Ways to Invoke a Function in Python – Lambda

The Man

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.

Sexy

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...

hello(“Matt”, “Hughes”)

But that's is so 90's.

Not Cool

"Hey nerd, did that function come with a free Beanie Baby??"

And ya I know python was invented in the 50's 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...

f = lambda x,y: print(“Hello World”+x+y)
f(“Matt”, “Hughes”)

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 obvious declared functions.

On the other hand, many will contest that the lambda funciton is MORE readable and contructive than it's generic counterpart.  In my opinion it comes down to a situational question.

A lamba 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 the contrary, and probably a good spot to contruct a Function in it's original intended shape.  (or an entire Class, but let's not get into that just yet.)

However you end up using it, lamda can be a fantastic, fast (and fun) alternative.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *