Quick Tip: Lambda Functions

Those of you that know me will know I am not a fan of Lambda functions. I just don’t buy into the notion of making code as concise as possible at the detriment of readability. To show you what I mean, I have written two functions. One is a Lambda function and the other is not.

In the non-Lambda version, you are left in no doubt as to what the function is doing. It’s looping over a list of numbers and it’s printing out the number multiplied by itself. It is true that the Lambda function is more concise, but ultimately it does the same thing but sacrifices readability.

####### LAMBDA VERSION
nums = [1,2,3]
f = lambda x: print(x*x)
[f(x) for x in nums]

####### NON LAMBDA VERSION
nums = [1,2,3]
def f(nums):
  for num in nums:
    print(num * num)
f(nums)

My own thoughts on Lambda aside, let’s look at some functions and understand what is going on.

In the below, we have a simple function which we have called add. Here we take an input value which we call X and we output X+5. In this example, we have input 7 and hence the output will be 12.

add = lambda x: x+5
print(add(7))

Getting a little more complex, we can take multiple input values. Here, we define those as x, y and z and we pass 7, 14 and 22 into the function. The result then, is 17+14+22 = 43.

add = lambda x,y,z: x+y+z
print(add(7, 14, 22))

Finally, we will look at the example at the top of this post. Here, the lambda function takes in X which is a number within the nums list. So, we’re saying ‘for each number in the numbers list, call the function f’. So the flow is:

  • f(1) = 1
  • f(2) = 4
  • f(3) = 9
nums = [1,2,3]
f = lambda x: print(x*x)
[f(x) for x in nums]

That is a little crash course into Lambda functions!

Kodey