Why even use lambda function in Python if normal functions can do the same thing?

Because lambdas can make your code way more readable.

First off, here's how it works.

A normal function that takes any number and returns its double looks like this.

def double(n):
		return n * 2

With lambda, it becomes this.

lambda n: n * 2

Lambda functions are anonymous, meaning they don't have a function name.

It just takes an argument n and returns n times two.

So when do you use it?

Lambda functions are best used as a callback. Meaning functions passed as an argument to another function that you probably only need once.

def fn(callback):
    callback()

fn(lambda: print("Hello from lambda!"))

Here’s a list of user, and we want to sort them by their age.

def get_age(person):
    return person['age']

people = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
sorted_people = sorted(people, key=get_age)

To do that, we pass a function as a key to the sort function.

It works. But with lambda functions, you can do the same thing in one line.

sorted_people = sorted(people, key=lambda person: person['age'])

Once you start using them, you'll wonder how you ever lived without them.

Keep Reading

No posts found