Lamda Functions in Python

Myself being from .net world, I got suprised to find out that python supports lambda function. Just like in .net a lambda function is a small anonymous function in python.

A simple example below.

add = lambda x, y: x + y

result = add(3, 5)
print(result) # Output: 8

They are often used for short, simple operations that can be defined in a single line of code. And this is what most of the tutorials say how you should use it.

However I think you should use it when you want your function to be used once, and code should reflect domain logic more than code logic. Confusing?

Let me give you an example. Lets say we want to get list of first name of employees. I have seen logic goes like this most of the time.

class Employee:
def __init__(self, employee_name, employee_id):
self.employee_name = employee_name
self.employee_id = employee_id

employees = [Employee("Bob A", 1), Employee("Tom B", 2), Employee("Lisa C", 3)]

for employee in employees:
print(employee.employee_name.split()[0])

For whoever seeing the code for the first time, code runs in the mind and interpreted as extracting the first name. Now check the refined code with lambda below.

firstNameOf = lambda employee: employee.employee_name.split()[0]
for employee in employees:
print(firstNameOf(employee))

We save some computation running inside brain by refining it with lambda. One can easily say the code is taking the first name of the employee.

Remember, majority time is not spent on writing new code, but in understanding existing code. When you convert time into money, you will get the point.

Leave a comment