Skip to content

Instantly share code, notes, and snippets.

@baileythegreen
Last active April 3, 2022 12:03
Show Gist options
  • Save baileythegreen/4cd4b63fe262d19fb07c0d2daa6bda95 to your computer and use it in GitHub Desktop.
Save baileythegreen/4cd4b63fe262d19fb07c0d2daa6bda95 to your computer and use it in GitHub Desktop.
Explanation of lambda function
def myfunc(n):
    return lambda a: a * n

mydoubler = myfunc(2)

mydoubler(5)

The first part of this defines a function which returns lambda a: a * n:

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

Lambdas are anonymous functions that can be useful in situations such as the ones Science done right outlines, as well as others. They can be difficult for people to follow, though. (I'm a fan, but I do try to think about their effect on readability for others.)

If you run myfunc(2) without assigning its return value anywhere, you get this:

<function __main__.myfunc.<locals>.<lambda>(a)>

This is partially evaluated; by calling myfunc(2), you are setting the value of n in the function to 2, but the value of the lambda function's variable a remains unset.

You can assign this partially-evaluated function to a name, like so:

mydoubler = myfunc(2)

Then, you can call the name you just defined like a function, passing it a value that will be assigned to a from the original definition:

mydoubler(5)  # returns 10
mydoubler(11)  # returns 22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment