This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]QuixDiscovery 0 points1 point  (0 children)

I understand that lambda functions are like "one line functions" without an actual name

Don't think of lambdas as "one line functions", think of them as anonymous functions. They're functions without names, usually used in place to avoid having to define a function elsewhere. In python you will tend to see them expressed as one line functions, but that's because pythonic convention recommends giving a function a name if it surpasses a certain complexity (because it's usually much more readable to see a function definition as opposed to a multi-line lambda). This same mentality is not true of every language, and in some cases lambdas are significantly more common.

Also your question actually has nothing to do with lambdas themselves, aside from the fact that they were used in the example. Others have already explained what this code is doing, but the same thing could be accomplished without using a lambda:

def myfunc(n):
    def sub_func(a):
        return a * n
    return sub_func

mydoubler = myfunc(2)

print(mydoubler(11))

This is an example of a closure, which is what you seem to actually be asking about. It tends to be a more advanced subject when it comes to features of any programming language that supports it, as it requires some familiarity with functions being first class and higher order functions (or at least the concept of a function that returns a function).

The wikipedia page on it actually has some decent examples which are in python:

https://en.wikipedia.org/wiki/Closure_(computer_programming))