Last Updated: February 25, 2016
· suhailsherif

Functional Python

Try using functional programming and lambda functions (anonymous one line one time usage functions that you need not waste namespace defining) while programming in Python.
It increases efficiency and better represents your code's function.

Eg (random): Calc e^x + 1 for all natural x in [1,10]. Take the values which have an even greatest integer value and find their product.

Step 1: Finding function values

fvals = [math.e**x + 1 for x in range(1,11)]


fvals = map(lambda x: e**x + 1, range(1,11))

Step 2: Keeping only even values.

fevenvals = filter(lambda x: int(x)%2==0, fvals)

Step 3: Go through the list multiplying elements together.

answer = reduce(lambda x,y: x*y, fevenvals)

In my opinion, the above is way more elegant, simple and clear than

answer = 1.0
for i in xrange(1,11):
  t = math.e**i + 1
  if int(t)%2==0:

2 Responses
Add your response

What do you mean "One time use" in the context of lambdas? They're first class objects.

over 1 year ago ·

@richoh I meant that you need not assign them a variable. So in that case, as anonymous functions, you can't access them after that one line.

over 1 year ago ·