Anatomy of a Lambda

It sounds so simple, why does it seem to confuse so many? From section 6.13 of the python docs. “The expression lambda arguments: expression yields a function object… Note that functions created with lambda expressions cannot contain statements or annotations.”   So first let’s take a look at the simple components of this abbreviated, “inline” function (an unnamed function) and then see a couple of contrived examples to show how it works.

Here is a breakdown of lambda “in the wild”, used in a filter command. See Demo #2 below to check this out in context. Note that this is “current” Python where filter is an iterator, not “archaic” (2.x) Python where the filter and map commands create a list.

Here is the easiest possible example to understand:

myLamNumber = lambda x:x*2
print(myLamNumber (5))

If you run this in idle it will report something like:
========= RESTART: D:\Documents\wikiPython\examples code\temptest.py =========
10
>>>

The basic formula for compound interest is pretty easy, lets see how lambda might respond if we have a maximum investment period of 5 years.

#Lambda example: Future Value = principal(1+(annual interest rate/compound frequency))**(years invested*compound frequency)
#Let say we aquire these values for our Future Value calculation but 5 years is our max investment term
p=1111.11  #  principal ($1M)
r=.05      #  annual interest rate (5%)
n=12.0     #  compounding periodicity (monthly)
t=0.0      #  years money is invested (8)
t=float(input("How many years do you want to invest? "))
future_value=lambda p,r,n,t: "$"+str(round(p*(1+(r/n))**(n*t),2))if t<=5 else " Sorry, 5 is the maximum investment period."
print("Your investment becomes :"+ future_value(p,r,n,t))

Now let’s assume your contacts are in a tuple called “ContactTuple” and you need a list of all those that start with the letter “G”. You could use a lambda function inside a filter command to put those names in a list.

#Lambda in a filter command example 2
ContactTuple =('Abe','Greg','Charlie','George', 'Bob', \
 'Dave','Don','Frank','Gilley')
SelectedContacts=filter(lambda x: x[0]=="G", ContactTuple)
#this creates a filter iterator called SelectedContacts
Nextcontact=""
  GContacts=[]
while Nextcontact is not "end":
 Nextcontact=next(SelectedContacts,"end")
 if Nextcontact is not "end":
   GContacts.append(Nextcontact)
 else:
   pass
print(GContacts)

…and that’s all there really is to it. For clarity’s sake you might be better off just writing a brief standard function but if it is used just one time, maybe lambda is more concise code. Of course, this contrived situation is just for an example and in this example a list comprehension would be a much easier, clearer solution:

NewList=[name for name in ContactTuple if name[0]=="G"]