Knowee
Questions
Features
Study Tools

What is anonymous function? Explain closure of function with example.

Question

What is anonymous function? Explain closure of function with example.

🧐 Not the exact question you are looking for?Go ask a question

Solution

An anonymous function is a function that is defined without a name. While normal functions are defined using the 'def' keyword in Python, anonymous functions are defined using the 'lambda' keyword. Hence, anonymous functions are also called lambda functions.

Here is a simple example of an anonymous function that adds two numbers:

sum = lambda a, b: a + b
print(sum(3, 4))  # Output: 7

A closure in Python is a tuple of variables that are created by a function whenever it is called. These variables will still exist after the function has finished executing, which is why they are called 'closures'. The function can then use these 'closed over' variables whenever it is called again.

Here is an example of a closure in Python:

def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function

closure = outer_function(10)
print(closure(5))  # Output: 15

In this example, outer_function is called with x = 10. It defines inner_function and then returns it. The returned function is a closure that 'closes over' the variable x, which remains available to it. When closure is later called with y = 5, it is able to access x and add it to y.

This problem has been solved

Similar Questions

What is a closure in JavaScript?Explanation:A function that is closed for modificationA function that captures and remembers its outer scopeA function that is accessible from any part of the codeA function with no parameters

What does the "closure" refer to in JavaScript?OptionsA function that has no parametersA function that returns a valueA function with a callback parameterA function nested inside another function that has access to the outer function's variables

Explain the concept of closures in JavaScript.(2 Points)A way to hide variables from the global scopeFunctions that have access to variables from their outer scopeA type of loop in JavaScriptA method to close browser windows in JavaScript

Explain inline function & Function overloading with example.

In call by value, what does the function receive as a parameter?

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.