DEV Community

Discussion on: Python Lambda functions

Collapse
 
waylonwalker profile image
Waylon Walker

Thanks for the shout out Chris! The real power of the lambda function comes when you need to pass a function to something else and that function is so simple it does not need to be declared. Most often I find myself reaching for them when using with a library that wants a function passed it, so its kind of hard to come up with a great example.

Lets say I have a list of tuples that I want to multiply together.

numbers = [(1, 2), (2, 4), (1, 4), (7, 8)]
Enter fullscreen mode Exit fullscreen mode

I can map over the list with an inline lambda

map(lambda x: x[0] * x[1], numbers)
Enter fullscreen mode Exit fullscreen mode

These days though I would use a list comprehension

[x * y for x, y in numbers]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dailydevtips1 profile image
Chris Bongers

Hey Waylon,

As fate shows us, I just finished a article on the filter() function and indeed used Lambda for the shorthand one!
What a cool feature I must say.