Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Question: What is Python Closures?
Answer:

As we have already discussed, closure is a nested function that helps us access the outer function's variables even after the outer function is closed. For example,

def greet():
    # variable defined outside the inner function
    name = "John"
    
    # return a nested anonymous function
    return lambda: "Hi " + name

# call the outer function
message = greet()

# call the inner function
print(message())

Output:

Hi John

In the above example, we have created a function named greet() that returns a nested anonymous function.

Is it helpful? Yes No

Most helpful rated by users:

©2025 WithoutBook