Syntax of the Lambda function

Asked

Viewed 684 times

0

I’m right at the beginning of the Lambda function study and I’m pretty much lost. I know the code could be done only with the "sum" function but I want to learn the Lambda syntax.

a = []
for b in range(0, 4):
    c = int(input())
    a.append(c)
d = (lambda x, y: x + y, a)
print(d)

The program has to take four typed numbers and show the sum and I think the error is on line 5. How that line would look to sum up all the numbers stored in the list?

1 answer

3


lambda in Python is not a function. It is a keyword that allows defining a function as an expression, or part of an expression. When you use the lambda, we say that you have created a new function, and to shorten we call the function maid using the lambda "lambda function"

In this case, the line d = (lambda x, y: x + y, a) actually neither creates only the lambda function - as the precedence of "," is less than that of lambda (the comma is solved after the lambda is already defined), this expression actually creates a tuple, in which the first item will be the lambda function lambda x, y: x + y and the second item will be a.

But from what I can tell from your show, it’s not lambda that interests you - you want to apply the function that sums x and y to all elements of a - what makes this is the function reduce.

The function reduce yes, it takes three parameters: A function in the first parameter, a sequence in the second, and an initial value in the third parameter. The function passed as the first parameter will always receive two arguments: the first being the "accumulated result" and the second being the "next item in the sequence". Thus, it is very common to use a lambda construction to create the function that goes in the first parameter of the call to reduce.

TL;DR: What you want on this show is this:

from functools import reduce
...
d = reduce(lambda x, y: x + y, a, 0)

What does it do? As in the case you used, the "," terminates the lambda - but in this case, it serves to separate the lambda from the next argument to the function reduce. And the 0 is the value used for the x in the first call the function, which is called once for each element in a, which will always be attributed to y. Functions defined with lambda do not need a return: the result of the only expression they contain is already its return value - and what reduces it does is put that value as x next call - until the elements of "a" are finished - the last value that the lambda function returns is returned by reduce.

Just so we’re clear, figure out what to use lambda is exactly the same thing as creating a normal function, with def and use the name of that function where the lambda; That is, this code could also be:

...
def soma2(x, y):
    return x + y

d = reduce(soma2, a, 0)

In short: both reduce and lambda are concepts that can be confusing if it is not absolutely clear to the programmer. If this is the case, it is better to avoid them and exchange them for the code "in full" equivalent, which is much simpler to understand, in general, both for those who write, and for those who read. There are more situations where you use "lambda" in the real world - sometimes we need a function to actually do something very simple - be it creating a new list object when you create a "defaultdict", or a calculation for the key value in an sort when you call the "Sorted". Already reduce is something more restricted to works of type "map-reduce" - if it is something simple, it is worth to unfold in three lines for readability. If it’s something very computational-intensive, it’s worth using a map-reduce library, like the Hadoop tools or pandas. So much so that in the transition to Python 3, reduce is no longer a builtin and has to be imported from the module functools.

The full reduce could be something like:

d = 0
for elemento in a:
   d = soma2(d, elemento)

but note that for this simple case, you don’t really win much with the so-called soma2 function - on the contrary, it loses readability. Then the most normal thing will be for you to write:

d = 0
for elemento in a:
    d += elemento

There is still a small performance gain because it is not called an intermediate function. The idea of reduce is more for languages with more emphasis on the functional (or purely functional) programming paradigm, where it is more normal to need to pass functions as parameters (some functional languages, at the extreme, do not even have an equivalent to for - you have to use functions as function parameters including to emulate a loop, as in Haskell or Scheme). They are very cool as an exercise, and understand different ways to approach problems, but in practice they require much more expenditure of "mental energy" than a simple interactive loop, as above.

Having said all this: lambda, map, filter and reduce are a small fraction of what exists in the "functional" programming paradigm. Python allows a better expressiveness than the map and filter using the list comprehensions and Generator Expressions (ex.: [x * 2 for x in range(10)]) - but the reduce only exists as a function even. If you want to explore this paradigm more, there is a very cool project on top of Python, called "Coconut". It creates a new language that is a Python superset (and in fact, the Coconut files are compiled for Python and run with the normal Python Runtime). Coconut defines dozens of tools and functions, plus an extended syntax, more suitable for functional programming:

http://coconut-lang.org/

  • Zero at the end does something?

  • yes - it serves as the starting value for the argument "x".

  • I’m not getting to import the intertools

  • 1

    Well, you might have better luck with itertools instead of intertools - but only a little more luck. Why the reduce is defined in functools, not in itertools

Browser other questions tagged

You are not signed in. Login or sign up in order to post.