DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

AndrΓ©s Baamonde Lozano
AndrΓ©s Baamonde Lozano

Posted on

Lambda expressions

The principal purpouse of this operator is declare anonymous functions(throw-away functions).

General syntax

argument list : expression

Examples

A typical example of lambda expressions is the use of arithmetic expressions but this operator can be used in a lot of situations

f = lambda x, y: x + y
f(1,2)
# outPut : 3
Enter fullscreen mode Exit fullscreen mode
f = lambda x: x[0]
f([2,3,4,5,6,7])
# outPut : 2
Enter fullscreen mode Exit fullscreen mode
f = lambda x, y: x if x < y else y
f(1,2)
# outPut : 2
Enter fullscreen mode Exit fullscreen mode

You can do a fast implement of tiny usefull functions, like len():

size = lambda x : 1 + size(x[1:]) if x != [] else 0
size([1,2,3])
# outPut : 3
Enter fullscreen mode Exit fullscreen mode

By itself, lambda operator is very useful, but we can seriously take advantage of it combining it with list/dict comprehension, maps, reduces and filters. In that case we will see the real power of this operator.

Top comments (0)

Top Heroku Alternatives (For Free!)

Recently Heroku shut down free Heroku Dynos, free Heroku Postgres, and free Heroku Data for Redis on November 28th, 2022. So Meshv Patel put together some free alternatives in this classic DEV post.