Python Lambda

Posted Thursday, 20 August 2009 at 16:44 by Andrew Liu
Tagged: python | web development
Read more blogs...

 

Using the lambda function in Python can be a little daunting, and I've always strayed away from it in the past.  It is very useful in doing calculations on the fly, and some applications of the Python lambda function can include reporting calculations, strenuous accounting functions, and number intensive programs.  Fortunately for me, I've kept away from those sorts of applications, and lambda is something that I know of, have used on the odd occasion, but never really fully understood it.

 

Today, I needed to use it, so I thought I'd dig up some of the documentation I've read on it in the past, go over it in more detail, and finally understand it enough so I can say that I've mastered it.

 

In short, lambda allows you to create an on-the-fly function.  Think of a once-off function - something that you would use briefly, then disregard.  Its similar to using that "i" variable in a loop; something that you simply need quickly to serve for a short purpose, then your program moves on.

 

In that sense, these extracts of Python code serve exactly the same purpose:

 

>>> def f (x): return x**2
...
>>> print f(8)
64
>>>
>>> g = lambda x: x**2
>>>
>>> print g(8)
64

 

Both extracts of Python code serve to produce the square of the given input parameter.  So whats the difference between these?

 

Firstly, the lambda function has no return function.  It always contains an expression which is always returned. 

 

Secondly, the lambda function is completed in a single line, whereas the function definition can span over multiple lines.  You cannot make a lambda function span multiple lines; it must be a single pythonic expression.  The result of that expression is the returned value for the lambda function.

 

To clear things up, lambda will return you a function, as show here:

 

>>> type(f)
<type 'function'>
>>> type(g)
<type 'function'>
>>>

 

Thus, the resulting function can be used anywhere else a function is expected, and will work in exactly the same way.

 

So where does this come in handy?  In my honest opinion, it isn't really that handy, because you can define a function which does the same thing, albeit in a few more lines of code.  I would think some Python purists would argue that the lambda function is "more correct" in some instances, and I would agree with this as well.  It can be very useful in streamlining Python code.  Perhaps the best example of this is when you look at the following problem, and the solutions I produce.

 

Problem

 

I have given sentence of varying length, and I would like to know how long each word is in that sentence.

 

Solution

 

Using "classical" Python (that is, using no lambda), this can be easily achieve in a series of loops as follows:

 

>>> a = "I have given sentence of varying length, and I would like to know how long each word is in that sentence."
>>> words = a.split(" ")
>>> lengths = []
>>> for word in words:
...     lengths.append(len(word))
...
>>> lengths
[1, 4, 5, 8, 2, 7, 7, 3, 1, 5, 4, 2, 4, 3, 4, 4, 4, 2, 2, 4, 9]
>>>

 

I could streamline this a bit with some smart do-it-one-line python, as follows:

 

>>> a = "I have given sentence of varying length, and I would like to know how long each word is in that sentence."
>>> words = a.split(" ")
>>> lengths = [ len(word) for word in words ]
>>> lengths
[1, 4, 5, 8, 2, 7, 7, 3, 1, 5, 4, 2, 4, 3, 4, 4, 4, 2, 2, 4, 9]
>>>

 

I can also achieve the same result using a lambda function, as follows:

 

>>> a = "I have given sentence of varying length, and I would like to know how long each word is in that sentence."
>>> words = a.split(" ")
>>> lengths = map(lambda x: len(x), words)
>>> lengths
[1, 4, 5, 8, 2, 7, 7, 3, 1, 5, 4, 2, 4, 3, 4, 4, 4, 2, 2, 4, 9]
>>>

 

In essence, all three solutions do the same thing, but hopefully you can see the benefit in using one of the last 2 solutions.  I personally favour the second solution, instead of using lambda, because it is a combination of "for" and "lists" that keep the code close to heart, instead of using a lambda function.  But there are cases when you must use a function (eg. when you actually pass functions around), and in this case, a lambda is the better solution all round.

 

 

 

 

Web News

Symantec distrust to begin in Chrome from April 2018
Google's browser will start the process of removing trust from old Symantec TLS certificates in Chrome 66.
--- 28 Jul 2017 01:42 PM

Ok Google: Telstra adds Google Home to smart home offering
The telco giant has welcomed Google into its Smart Home play.
--- 28 Jul 2017 01:08 PM

Huawei reports 15 percent revenue surge for H1 2017
The networking giant generated 283.1 billion yuan in revenue during the first six months of 2017.
--- 28 Jul 2017 12:47 PM

LG posts healthy Q2 profit despite mobile setback
Marketing costs for the new G6 tinted an otherwise strong quarter for LG Electronics.
--- 28 Jul 2017 11:53 AM

Singapore should not criminalise good intent to encourage data sharing in cybersecurity
People who fear prosecution may be less willing to share threat information, which is vital in fending off attacks, and Singapore government should clearly define its proposed mandate for companies to report data breaches within 72 hours.
--- 28 Jul 2017 11:23 AM

Company Blog


Search Behaviour

Posted Tuesday, 19 October 2010 at 05:58 by Andrew Liu


As an SEO provider, you have one main goal. Get your clients website to show up in search results fo...

Read more...



sm bus drivers missing in Device Manager

Posted Sunday, 18 April 2010
Updated Sunday, 24 February 2013 at 06:39 by Andrew Liu


When installing a new Windows XPinstallation, I seemingly always miss some drivers. One that trouble...

Read more...



Multiple Domains for SEO performance?

Posted Friday, 05 March 2010 at 23:13 by Andrew Liu


Online businesses and websites that cover a broad range of topics or one large topic are sometimes b...

Read more...



Tag Clouds - SEO or not?

Posted Thursday, 04 March 2010 at 04:34 by Andrew Liu


A tag cloud or word cloud is a visual depiction of tags or words related to a site, typically used t...

Read more...



Mozilla Thunderbird and Gmail IMAP Attachments Bug

Posted Wednesday, 03 March 2010 at 20:15 by Andrew Liu


I've been using Gmail since its early inception, and Iwas one of the first to utilise Gmail's IMAPfe...

Read more...



Read more blogs...