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

Data stolen from Hy-Vee customers offered for sale on Jokers Stash Dark Web forum
A card dump of 5.3 million accounts may be tied to the recent security breach.
--- 23 Aug 2019 08:15 PM

Linux on your laptop: A closer look at EFI boot options
A review of what EFI boot (UEFI firmware) is, how it works, how it interacts with Linux installations, and a few tips and personal experiences on how to configure and maintain it.
--- 23 Aug 2019 08:04 PM

80 suspects arrested in massive business email scam takedown
Police say the mainly-Nigerian network was responsible for the attempted theft of $46 million.
--- 23 Aug 2019 07:22 PM

South Korea pulls out of intel sharing pact with Japan amid trade dispute
Withdrawing from an intelligence sharing agreement with Japan alarmingly expands the scope of their trade dispute beyond being purely political and economic, making it also about security.
--- 23 Aug 2019 01:02 PM

What Amazon Web Services security certification is doing for government
The Australian government is now getting its hands on new technologies to improve citizen experiences.
--- 23 Aug 2019 11:35 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...