# đź“° Lambda functions in Python: Para que elas servem?

Fonte: mail from Dan Bader PythonTricks

Hey Hans R Zimermann,

I got some questions about Python’s “lambda” expressions: What theyâ€™re good for, when you should use them, and when itâ€™s best to avoid them.

So I decided to write a little tutorial for you:

TheÂ `lambda`Â keyword in Python provides a shortcut for declaring small anonymous functions. Lambda functions behave just like regular functions declared with theÂ `def`Â keyword. They can be used whenever function objects are required.

For example, this is how youâ€™d define a simple lambda function carrying out an addition:

```>>> add = lambda x, y: x + y
8
```

You could declare the sameÂ `add`Â function with theÂ `def`Â keyword:

```>>> def add(x, y):
...     return x + y
8
```

Now you might be wondering:Â Why the big fuss about lambdas?Â If theyâ€™re just a slightly more terse version of declaring functions withÂ `def`, whatâ€™s the big deal?

Take a look at the following example and keep the wordsÂ function expressionÂ in your head while you do that:

```>>> (lambda x, y: x + y)(5, 3)
8
```

Okay, what happened here? I just usedÂ `lambda`Â to define an â€śaddâ€ť function inline and then immediately called it with the argumentsÂ `5`Â andÂ `3`.

Conceptually theÂ lambda expressionÂ `lambda x, y: x + y`Â is the same as declaring a function withÂ `def`, just written inline. The difference is I didnâ€™t bind it to a name likeÂ `add`Â before I used it. I simply stated the expression I wanted to compute and then immediately evaluated it by calling it like a regular function.

Before you move on, you might want to play with the previous code example a little to really let the meaning of it sink in. I still remember this took me a while to wrap my head around. So donâ€™t worry about spending a few minutes in an interpreter session.

Thereâ€™s another syntactic difference between lambdas and regular function definitions: Lambda functions are restricted to a single expression. This means a lambda function canâ€™t use statements or annotationsâ€”not even aÂ `returnÂ `statement.

How do you return values from lambdas then? Executing a lambda function evaluates its expression and then automatically returns its result. So thereâ€™s always anÂ implicitÂ return statement. Thatâ€™s why some people refer to lambdas asÂ single expression functions.

### Lambdas You Can Use

When should you use lambda functions in your code? Technically, any time youâ€™re expected to supply a function object you can use a lambda expression. And because a lambda expression can be anonymous, you donâ€™t even need to assign it to a name.

This can provide a handy and â€śunbureaucraticâ€ť shortcut to defining a function in Python. My most frequent use case for lambdas is writing short and conciseÂ key funcsÂ forÂ sorting iterables by an alternate key:

```>>> sorted(range(-5, 6), key=lambda x: x ** 2)
[0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5]
```

Like regular nested functions, lambdas also work asÂ lexical closures.

Whatâ€™s a lexical closure? Just a fancy name for a function that remembers the values from the enclosing lexical scope even when the program flow is no longer in that scope. Hereâ€™s a (fairly academic) example to illustrate the idea:

```>>> def make_adder(n):
...     return lambda x: x + n

>>> plus_3(4)
7
>>> plus_5(4)
9
```

In the above example theÂ `x + n`Â lambda can still access the value ofÂ `n`Â even though it was defined in theÂ `make_adder`Â function (the enclosing scope).

Sometimes, using a lambda function instead of a nested function declared withÂ `def`Â can express oneâ€™s intent more clearly. But to be honest this isnâ€™t a common occurrenceâ€”at least in the kind of code that I like to write.

### But Maybe You Shouldnâ€™tâ€¦

Now on the one hand Iâ€™m hoping this tutorial got you interested in exploring Pythonâ€™s lambda functions. On the other hand I feel like itâ€™s time to put up another caveat: Lambda functions should be used sparingly and with extraordinary care.

I know I wrote my fair share of code using lambdas that looked â€ścoolâ€ť but was actually a liability for me and my coworkers. If youâ€™re tempted to use a lambda spend a few seconds (or minutes) to think if this is really the cleanest and most maintainable way to achieve the desired result.

For example, doing something like this to save two lines of code is just silly. Sure, it technically works and itâ€™s a nice enough â€śtrickâ€ť. But itâ€™s also going to confuse the next gal or guy having to ship a bugfix under a tight deadline:

```# Harmful:
>>> class Car:
...     rev = lambda self: print('Wroom!')
...     crash = lambda self: print('Boom!')

>>> my_car = Car()
>>> my_car.crash()
'Boom!'
```

I feel similarly about complicatedÂ `map()`Â orÂ `filter()`Â constructs using lambdas. Usually itâ€™s much cleaner to go with a list comprehension or generator expression:

```# Harmful:
>>> list(filter(lambda x: x % 2 == 0, range(16)))
[0, 2, 4, 6, 8, 10, 12, 14]

# Better:
>>> [x for x in range(16) if x % 2 == 0]
[0, 2, 4, 6, 8, 10, 12, 14]
```

If you find yourself doing anything remotely complex with a lambda expression, consider defining a real function with a proper name instead.

Saving a few keystrokes wonâ€™t matter in the long run. Your colleagues (and your future self) will appreciate clean and readable code more than terse wizardry.

### Things to Remember

• Lambda functions are single-expression functions that are not necessarily bound to a name (anonymous).
• Lambda functions canâ€™t use regular Python statements and always include an implicitÂ `return`Â statement.
• Always ask yourself:Â Would using a regular (named) function or a list/generator expression offer more clarity?