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

Rent the Runway CEO: Gender discrimination is larger workplace issue than sexual harassment
Jennifer Hyman runs a fast growing startup and helps women become successful in their businesses through Project Entrepreneur accelerator programs
--- 21 Oct 2017 10:26 AM

Vision is the next big challenge for chips
Neural engines are already showing up in phones and chipmakers are racing to develop more powerful hardware to meet demand for vision processing in a growing list of applications.
--- 21 Oct 2017 05:45 AM

Get a $1,000 software and services bundle for $49
Packed with tools designed for business growth, Briefcase offers tremendous value. There's just one catch.
--- 21 Oct 2017 04:56 AM

Elephone S8 hands-on: A solid, no-nonsense phone for business use
The Elephone S8 is a tri-bezel-less phone with a huge screen and a gorgeous glass back that is great for consumers and business users.
--- 21 Oct 2017 04:34 AM

Google expands tech startup acceleration projects in LatAm
The company is turning its So Paulo venue into a hub to foster ventures across the region.
--- 21 Oct 2017 03:40 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...