{"id":967,"date":"2020-11-05T08:41:50","date_gmt":"2020-11-05T08:41:50","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=967"},"modified":"2025-03-27T13:46:15","modified_gmt":"2025-03-27T13:46:15","slug":"python-closures","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/advanced-python\/python-closures\/","title":{"rendered":"Python Closures"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about Python closures and their practical applications.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-the-python-closures'>Introduction to the Python closures <a href=\"#introduction-to-the-python-closures\" class=\"anchor\" id=\"introduction-to-the-python-closures\" title=\"Anchor for Introduction to the Python closures\">#<\/a><\/h2>\n\n\n\n<p>In Python, you can define a <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-functions\/\">function<\/a> from the inside of another function. And this function is called a nested function. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">say<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n    greeting = <span class=\"hljs-string\">'Hello'<\/span>\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">display<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n        print(greeting)\n\n    display()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, we define the <code>display<\/code> function inside the <code>say<\/code> function. The <code>display<\/code> function is called a nested function.<\/p>\n\n\n\n<p>Inside the <code>display<\/code> function, you access the <code>greeting<\/code> variable from its <a href=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-nonlocal\/\">nonlocal scope<\/a>.<\/p>\n\n\n\n<p>Python calls the <code>greeting<\/code> variable a free variable.<\/p>\n\n\n\n<p>When you look at the <code>display<\/code> function, you actually look at:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>display<\/code> function itself.<\/li>\n\n\n\n<li>And the free variable <code>greeting<\/code> with the value <code>'Hello'<\/code>.<\/li>\n<\/ul>\n\n\n\n<p>So the combination of the <code>display<\/code> function and <code>greeting<\/code> variable is called a closure:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"391\" height=\"158\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/11\/Python-Closure-Example.png\" alt=\"\" class=\"wp-image-969\" srcset=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/11\/Python-Closure-Example.png 391w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/11\/Python-Closure-Example-300x121.png 300w\" sizes=\"auto, (max-width: 391px) 100vw, 391px\" \/><\/figure>\n\n\n\n<p>By definition, <strong>a closure is a nested function that references one or more variables from its enclosing scope.<\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='returning-an-inner-function'>Returning an inner function <a href=\"#returning-an-inner-function\" class=\"anchor\" id=\"returning-an-inner-function\" title=\"Anchor for Returning an inner function\">#<\/a><\/h3>\n\n\n\n<p>In Python, a function can return a value which is another function. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">say<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n    greeting = <span class=\"hljs-string\">'Hello'<\/span>\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">display<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n        print(greeting)\n\n    <span class=\"hljs-keyword\">return<\/span> display    \n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, the <code>say<\/code> function returns the <code>display<\/code> function instead of executing it.<\/p>\n\n\n\n<p>Also, when the <code>say<\/code> function returns the <code>display<\/code> function, it actually returns a closure:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"425\" height=\"177\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/11\/Python-Closures.png\" alt=\"\" class=\"wp-image-970\" srcset=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/11\/Python-Closures.png 425w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/11\/Python-Closures-300x125.png 300w\" sizes=\"auto, (max-width: 425px) 100vw, 425px\" \/><\/figure>\n\n\n\n<p>The following assigns the return value of the <code>say<\/code> function to a variable <code>fn<\/code>. Since <code>fn<\/code> is a function, you can execute it:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">fn = say()\nfn()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">Hello<\/code><\/span><\/pre>\n\n\n<p>The <code>say<\/code> function executes and returns a function. When the <code>fn<\/code> function executes, the <code>say<\/code> function already completes.<\/p>\n\n\n\n<p>In other words, the scope of the <code>say<\/code> function was gone at the time the <code>fn<\/code> function executes.<\/p>\n\n\n\n<p>Since the <code>greeting<\/code> variable belongs to the scope of the <code>say<\/code> function, it should also be destroyed with the scope of the function.<\/p>\n\n\n\n<p>However, you still see that <code>fn<\/code> displays the value of the <code>message<\/code> variable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='python-cells-and-multi-scoped-variables'>Python cells and multi-scoped variables <a href=\"#python-cells-and-multi-scoped-variables\" class=\"anchor\" id=\"python-cells-and-multi-scoped-variables\" title=\"Anchor for Python cells and multi-scoped variables\">#<\/a><\/h2>\n\n\n\n<p>The value of the <code>greeting<\/code> variable is shared between two scopes of:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>say<\/code> function.<\/li>\n\n\n\n<li>The closure<\/li>\n<\/ul>\n\n\n\n<p>The label <code>greeting<\/code> is in two different scopes. However, they always reference the same string object with the value <code>'Hello'<\/code>.<\/p>\n\n\n\n<p>To achieve this, Python creates an intermediary object called a <code>cell<\/code>:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/06\/Python-Closures.svg\" alt=\"\" class=\"wp-image-3543\"\/><\/figure>\n\n\n\n<p>To find the memory address of the cell object, you can use the <code>__closure__<\/code> property as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">print(fn.__closure__)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\">(<span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">cell<\/span> <span class=\"hljs-attr\">at<\/span> <span class=\"hljs-attr\">0x0000017184915C40:<\/span> <span class=\"hljs-attr\">str<\/span> <span class=\"hljs-attr\">object<\/span> <span class=\"hljs-attr\">at<\/span> <span class=\"hljs-attr\">0x0000017186A829B0<\/span>&gt;<\/span>,)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>__closure__<\/code> returns a tuple of cells.<\/p>\n\n\n\n<p>In this example, the memory address of the cell is <code>0x0000017184915C40<\/code>. It references a string object at <code>0x0000017186A829B0<\/code>.<\/p>\n\n\n\n<p>If you display the memory address of the string object in the <code>say<\/code> function and <code>closure<\/code>, you should see that they reference the same object in the memory:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">say<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n    greeting = <span class=\"hljs-string\">'Hello'<\/span>\n    print(hex(id(greeting)))\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">display<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n        print(hex(id(greeting)))\n        print(greeting)\n\n    <span class=\"hljs-keyword\">return<\/span> display\n\n\nfn = say()\nfn()\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=ZGVmIHNheSgpOgogICAgZ3JlZXRpbmcgPSAnSGVsbG8nCiAgICBwcmludChoZXgoaWQoZ3JlZXRpbmcpKSkKCiAgICBkZWYgZGlzcGxheSgpOgogICAgICAgIHByaW50KGhleChpZChncmVldGluZykpKQogICAgICAgIHByaW50KGdyZWV0aW5nKQoKICAgIHJldHVybiBkaXNwbGF5CgoKZm4gPSBzYXkoKQpmbigp\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">0x17186a829b0\n0x17186a829b0<\/code><\/span><\/pre>\n\n\n<p>When you access the value of the <code>greeting<\/code> variable, Python will technically &#8220;double-hop&#8221; to get the string value.<\/p>\n\n\n\n<p>This explains why when the <code>say()<\/code> function was out of scope, you still can access the string object referenced by the <code>greeting<\/code> variable.<\/p>\n\n\n\n<p>Based on this mechanism, you can think of <strong>a closure as a function and an extended scope that contains free variables.<\/strong><\/p>\n\n\n\n<p>To find the free variables that a closure contains, you can use the <code>__code__.co_freevars<\/code>, for example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">say<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n\n    greeting = <span class=\"hljs-string\">'Hello'<\/span>\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">display<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n        print(greeting)\n\n    <span class=\"hljs-keyword\">return<\/span> display\n\n\nfn = say()\nprint(fn.__code__.co_freevars)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=ZGVmIHNheSgpOgoKICAgIGdyZWV0aW5nID0gJ0hlbGxvJwoKICAgIGRlZiBkaXNwbGF5KCk6CiAgICAgICAgcHJpbnQoZ3JlZXRpbmcpCgogICAgcmV0dXJuIGRpc3BsYXkKCgpmbiA9IHNheSgpCnByaW50KGZuLl9fY29kZV9fLmNvX2ZyZWV2YXJzKQ%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">(<span class=\"hljs-string\">'greeting'<\/span>,)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, the <code>fn.__code__.co_freevars<\/code> returns the <code>greeting<\/code> free variable of the <code>fn<\/code> closure.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='when-python-creates-the-closure'>When Python creates the closure <a href=\"#when-python-creates-the-closure\" class=\"anchor\" id=\"when-python-creates-the-closure\" title=\"Anchor for When Python creates the closure\">#<\/a><\/h2>\n\n\n\n<p>Python creates a new scope when a function executes. If that function creates a closure, Python also creates a new closure as well. Consider the following example:<\/p>\n\n\n\n<p>First, define a function called <code>multiplier<\/code> that returns a closure:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">multiplier<\/span><span class=\"hljs-params\">(x)<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">multiply<\/span><span class=\"hljs-params\">(y)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> x * y\n    <span class=\"hljs-keyword\">return<\/span> multiply<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>multiplier<\/code> function returns the multiplication of two arguments. However, it uses a closure instead.<\/p>\n\n\n\n<p>Second, call the <code>multiplier<\/code> function three times:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">m1 = multiplier(<span class=\"hljs-number\">1<\/span>)\nm2 = multiplier(<span class=\"hljs-number\">2<\/span>)\nm3 = multiplier(<span class=\"hljs-number\">3<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>These function calls create three closures. Each function multiplies a number with 1, 2, and 3.<\/p>\n\n\n\n<p>Third, execute functions of the closures:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">print(m1(<span class=\"hljs-number\">10<\/span>))\nprint(m2(<span class=\"hljs-number\">10<\/span>))\nprint(m3(<span class=\"hljs-number\">10<\/span>))<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The m1, m2, and m3 have different instances of closure.<\/p>\n\n\n\n<p>Put it all together:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">def multiplier(x):\n    def multiply(y):\n        <span class=\"hljs-keyword\">return<\/span> x * y\n    <span class=\"hljs-keyword\">return<\/span> multiply\n\nm1 = multiplier(<span class=\"hljs-number\">1<\/span>)\nm2 = multiplier(<span class=\"hljs-number\">2<\/span>)\nm3 = multiplier(<span class=\"hljs-number\">3<\/span>)\n\n<span class=\"hljs-keyword\">print<\/span>(m1(<span class=\"hljs-number\">10<\/span>))\n<span class=\"hljs-keyword\">print<\/span>(m2(<span class=\"hljs-number\">10<\/span>))\n<span class=\"hljs-keyword\">print<\/span>(m3(<span class=\"hljs-number\">10<\/span>))<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=ZGVmIG11bHRpcGxpZXIoeCk6CiAgICBkZWYgbXVsdGlwbHkoeSk6CiAgICAgICAgcmV0dXJuIHggKiB5CiAgICByZXR1cm4gbXVsdGlwbHkKCm0xID0gbXVsdGlwbGllcigxKQptMiA9IG11bHRpcGxpZXIoMikKbTMgPSBtdWx0aXBsaWVyKDMpCgpwcmludChtMSgxMCkpCnByaW50KG0yKDEwKSkKcHJpbnQobTMoMTApKQ%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">10\n20\n30<\/code><\/span><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='python-closures-and-for-loop'>Python closures and for loop <a href=\"#python-closures-and-for-loop\" class=\"anchor\" id=\"python-closures-and-for-loop\" title=\"Anchor for Python closures and for loop\">#<\/a><\/h2>\n\n\n\n<p>Suppose that you want to create all three closures above at once and you might come up with the following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">multipliers = &#91;]\n<span class=\"hljs-keyword\">for<\/span> x in range(<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">4<\/span>):\n    multipliers.append(lambda y: x * y)\n\nm1, m2, m3 = multipliers\n\n<span class=\"hljs-keyword\">print<\/span>(m1(<span class=\"hljs-number\">10<\/span>))\n<span class=\"hljs-keyword\">print<\/span>(m2(<span class=\"hljs-number\">10<\/span>))\n<span class=\"hljs-keyword\">print<\/span>(m3(<span class=\"hljs-number\">10<\/span>))\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=bXVsdGlwbGllcnMgPSBbXQpmb3IgeCBpbiByYW5nZSgxLCA0KToKICAgIG11bHRpcGxpZXJzLmFwcGVuZChsYW1iZGEgeTogeCAqIHkpCgptMSwgbTIsIG0zID0gbXVsdGlwbGllcnMKCnByaW50KG0xKDEwKSkKcHJpbnQobTIoMTApKQpwcmludChtMygxMCkp\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>How it works:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, declare a list that will store the closures.<\/li>\n\n\n\n<li>Second, use a <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-lambda-expressions\/\">lambda expression<\/a> to create a closure and append the closure to the list in each iteration.<\/li>\n\n\n\n<li>Third, <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-unpack-list\/\">unpack<\/a> the closures from the list to the m1, m2, and m3 variables.<\/li>\n\n\n\n<li>Finally, pass the values 10, 20, and 30 to each closure and execute it.<\/li>\n<\/ul>\n\n\n\n<p>The following shows the output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">30\n30\n30<\/code><\/span><\/pre>\n\n\n<p>This doesn&#8217;t work as you expected. But why?<\/p>\n\n\n\n<p>The <code>x<\/code> starts from 1 to 3 in the loop. After the loop, its value is 3.<\/p>\n\n\n\n<p>Each element of the list is the following closure:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">lambda y: x*y<\/code><\/span><\/pre>\n\n\n<p>Python evaluates <code>x<\/code> when you call the <code>m1(10)<\/code>, <code>m2(10)<\/code>, and <code>m3(10)<\/code>. At the moment the closures execute, <code>x<\/code> is 3.<\/p>\n\n\n\n<p>That&#8217;s why you see the same result when you call <code>m1(10)<\/code>, <code>m2(10)<\/code>, and <code>m3(10)<\/code>.<\/p>\n\n\n\n<p>To fix this, you need to instruct Python to evaluate <code>x<\/code> in the loop:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">multiplier<\/span><span class=\"hljs-params\">(x)<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">multiply<\/span><span class=\"hljs-params\">(y)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> x * y\n    <span class=\"hljs-keyword\">return<\/span> multiply\n\n\nmultipliers = &#91;]\n<span class=\"hljs-keyword\">for<\/span> x <span class=\"hljs-keyword\">in<\/span> range(<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">4<\/span>):\n    multipliers.append(multiplier(x))\n\nm1, m2, m3 = multipliers\n\nprint(m1(<span class=\"hljs-number\">10<\/span>))\nprint(m2(<span class=\"hljs-number\">10<\/span>))\nprint(m3(<span class=\"hljs-number\">10<\/span>))\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=ZGVmIG11bHRpcGxpZXIoeCk6CiAgICBkZWYgbXVsdGlwbHkoeSk6CiAgICAgICAgcmV0dXJuIHggKiB5CiAgICByZXR1cm4gbXVsdGlwbHkKCgptdWx0aXBsaWVycyA9IFtdCmZvciB4IGluIHJhbmdlKDEsIDQpOgogICAgbXVsdGlwbGllcnMuYXBwZW5kKG11bHRpcGxpZXIoeCkpCgptMSwgbTIsIG0zID0gbXVsdGlwbGllcnMKCnByaW50KG0xKDEwKSkKcHJpbnQobTIoMTApKQpwcmludChtMygxMCkp\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A closure is a function and an extended scope that contains free variables.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"967\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-closures\/\"\n\t\t\t\tdata-post-title=\"Python Closures\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"967\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-closures\/\"\n\t\t\t\tdata-post-title=\"Python Closures\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn about Python closures and their practical applications.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":757,"menu_order":8,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-967","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/967","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=967"}],"version-history":[{"count":1,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/967\/revisions"}],"predecessor-version":[{"id":7110,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/967\/revisions\/7110"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/757"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=967"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}