Python Closures Last Updated : 11 Dec, 2024 Comments Improve Suggest changes Like Article Like Report In Python, a closure is a powerful concept that allows a function to remember and access variables from its lexical scope, even when the function is executed outside that scope. Closures are closely related to nested functions and are commonly used in functional programming, event handling and callbacks.A closure is created when a function (the inner function) is defined within another function (the outer function) and the inner function references variables from the outer function. Closures are useful when you need a function to retain state across multiple calls, without using global variables.A Basic Example of Python ClosuresLet's break down a simple example to understand how closures work. Python def fun1(x): # This is the outer function that takes an argument 'x' def fun2(y): # This is the inner function that takes an argument 'y' return x + y # 'x' is captured from the outer function return fun2 # Returning the inner function as a closure # Create a closure by calling outer_function closure = fun1(10) # Now, we can use the closure, which "remembers" the value of 'x' as 10 print(closure(5)) Output15 Explanation:Outer Function (fun1): Takes an argument x and defines the fun2. The fun2 uses x and another argument y to perform a calculation.Inner Function (fun2): This function is returned by fun1 and is thus a closure. It "remembers" the value of x even after fun1has finished executing.Creating and Using the Closure: When you call fun1(10), it returns fun2 with x set to 10. The returned fun2(closure) is stored in the variable closure. When you call closure(5), it uses the remembered value of x (which is 10) and the passed argument y (which is 5), calculating the sum 10 + 5 = 15.Let's take a look at python closure in detail:Example of Python closure: Python def fun(a): # Outer function that remembers the value of 'a' def adder(b): # Inner function that adds 'b' to 'a' return a + b return adder # Returns the closure # Create a closure that adds 10 to any number val = fun(10) # Use the closure print(val(5)) print(val(20)) Output15 30 In this example:fun(10) creates a closure that remembers the value 10 and adds it to any number passed to the closure.How Closures Work Internally?When a closure is created, Python internally stores a reference to the environment (variables in the enclosing scope) where the closure was defined. This allows the inner function to access those variables even after the outer function has completed.In simple terms, a closure "captures" the values from its surrounding scope and retains them for later use. This is what allows closures to remember values from their environment.Use of ClosuresEncapsulation: Closures help encapsulate functionality. The inner function can access variables from the outer function, but those variables remain hidden from the outside world. State Retention: Closures can retain state across multiple function calls. This is especially useful in situations like counters, accumulators, or when you want to create a function factory that generates functions with different behaviors.Functional Programming: Closures are a core feature of functional programming. They allow you to create more flexible and modular code by generating new behavior dynamically. Comment More infoAdvertise with us Next Article Python Closures kartik Follow Improve Article Tags : Python Practice Tags : python Similar Reads range() vs xrange() in Python The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python3, there is no xrange, but the range function behaves like xrange in Python2. If you want to write code that will run on both Python2 and Python3, you should use range( 4 min read Using Else Conditional Statement With For loop in Python Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while 2 min read Iterators in Python An iterator in Python is an object that holds a sequence of values and provide sequential traversal through a collection of items such as lists, tuples and dictionaries. . The Python iterators object is initialized using the iter() method. It uses the next() method for iteration.__iter__(): __iter__ 3 min read Iterator Functions in Python | Set 1 Perquisite: Iterators in PythonPython in its definition also allows some interesting and useful iterator functions for efficient looping and making execution of the code faster. There are many build-in iterators in the module "itertools". This module implements a number of iterator building blocks. 4 min read Converting an object into an iterator In Python, we often need to make objects iterable, allowing them to be looped over like lists or other collections. Instead of using complex generator loops, Python provides the __iter__() and __next__() methods to simplify this process.Iterator Protocol:__iter__(): Returns the iterator object itsel 5 min read Python | Difference between iterable and iterator Iterable is an object, that one can iterate over. It generates an Iterator when passed to iter() method. An iterator is an object, which is used to iterate over an iterable object using the __next__() method. Iterators have the __next__() method, which returns the next item of the object. Note: Ever 3 min read When to use yield instead of return in Python? The yield statement suspends a function's execution and sends a value back to the caller, but retains enough state to enable the function to resume where it left off. When the function resumes, it continues execution immediately after the last yield run. This allows its code to produce a series of v 2 min read Generators in Python Python generator functions are a powerful tool for creating iterators. In this article, we will discuss how the generator function works in Python.Generator Function in PythonA generator function is a special type of function that returns an iterator object. Instead of using return to send back a si 5 min read Python Functions Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov 11 min read Returning Multiple Values in Python In Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. Python # A Python program to return multiple # values from a meth 4 min read Like