DEV Community

Andrés Baamonde Lozano
Andrés Baamonde Lozano

Posted on

2 1

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more