{"id":21662,"date":"2021-08-28T16:26:44","date_gmt":"2021-08-28T16:26:44","guid":{"rendered":"https:\/\/www.askpython.com\/?p=21662"},"modified":"2026-09-29T17:10:23","modified_gmt":"2026-09-29T17:10:23","slug":"memoization-in-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/memoization-in-python","title":{"rendered":"Memoization in Python &#8211; A Brief Introduction"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">In this tutorial, we are going to discuss one of the very popular optimization techniques &#8211; Memoization in Python &#8211; primarily used to speed up computer programs. So, let&#8217;s get started!<\/p>\n\n\n\n<hr class=\"wp-block-separator is-style-default\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What is memoization in Python?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In the world of computer programming, <strong>Memoisation or Memoization in Python<\/strong> is a special kind of optimization technique that is primarily used to speed up our computer program. It effectively reduces the runtime of the computer program by storing the results of the expensive (in terms of runtime) function calls into the memory and using it whenever any stored or cached value is required.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It ensures that a particular function or method does need not run more than once for the same set of inputs as the results are already available as cached \/stored data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is similar to <strong>caching<\/strong>. It involves caching the return values of the function based on its input parameters.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In Python, we can implement the memoization technique in our programs using <strong><a href=\"https:\/\/www.askpython.com\/python\/examples\/decorators-in-python\" target=\"_blank\" rel=\"noreferrer noopener\">function and class-based decorators<\/a><\/strong>. And we will be using a <a href=\"https:\/\/www.askpython.com\/python\/python-recursion-function\" data-type=\"post\" data-id=\"438\">recursive Python program<\/a> to calculate the n<sup>th<\/sup> Fibonacci number in our whole discussion because for greater inputs this program will become very very slow because the number of function calls for the same input values increase with the input size.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Memoization in Python using function based decorators<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">It is the best and the complex way of implementing the memoization technique in Python, for those who want to understand how this optimization technique actually works. In this method of implementation of memoization technique, we define our own decorator function in Python to cache\/store the return values of the function calls. Let&#8217;s see how to write Python code to implement this.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Memoization using function-based decorators\n\ndef memoize(f):\n    cache = {}\n    def foo(x):\n        if x not in cache:\n            cache&#x5B;x] = f(x)\n        return cache&#x5B;x]\n    return foo\n\n@memoize\ndef fibonacci(n):\n    if n == 0:\n        return 0\n    elif n == 1:\n        return 1\n    else:\n        return fibonacci(n-1) + fibonacci(n-2)\n\n# Driver code\nfibonacci(20)\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n6765\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Memoization using class based decorators<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">It is the second-best and the complex way of implementing the memoization technique in Python, for beginners who want to understand how this optimization technique actually works. In this method of implementation of memoization technique, we define our own decorator class in Python to cache\/store the return values of the function calls. Let&#8217;s write Python code to implement this.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Memoization using class-based decorators\n\nclass classMemoize:\n    def __init__(self, f):\n        self.f = f\n        self.cache = {}\n    def __call__(self, *x):\n        if x not in self.cache:\n            self.cache&#x5B;x] = self.f(*x)\n        return self.cache&#x5B;x]\n\n@classMemoize\ndef fibonacci(n):\n    if n == 0:\n        return 0\n    elif n == 1:\n        return 1\n    else:\n        return fibonacci(n-1) + fibonacci(n-2)\n\n# Driver code\nfibonacci(50)\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n12586269025\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Memoization using built-in decorator functions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">It is one of the simple and the easiest way to implement the memoization technique in Python. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this method of implementation of memoization technique, we do not define our own decorator function or class but we make use of the built-in functions like <code>lru_cache()<\/code> and <code>cache()<\/code> to cache\/store the intermediate results of a function call. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These  <code>lru_cache()<\/code> and <code>cache()<\/code> functions are defined in the <code>funtools<\/code> library which is a standard Python library and it comes with the normal Python installation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The  <code>lru_cache(maxsize=None, typed=False)<\/code> function offers some customization features through its parameters like <code>maxsize<\/code> and <code>typed<\/code>. The parameter <code>maxsize<\/code> decides if the LRU features will be enabled or not by setting its value either <strong>None<\/strong> or an integer <strong>value<\/strong>. And the parameter <code>typed<\/code> decides if the different types of data are to be cached separately or not.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An integer Value will limit the size of the cache maintained during the execution of the Python program and the None value will disable the LRU features and then the cache can grow without any bound.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>cache()<\/code> function is available from the Python 3.9 release onwards and it is equivalent to the <code>lru_cache(maxsize=None)<\/code> function in the <code>funtools<\/code> library.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Memoization using built-in function\n\nimport functools\n\n@functools.cache\ndef fibonacci(n):\n    if n == 0:\n        return 0\n    elif n == 1:\n        return 1\n    else:\n        return fibonacci(n-1) + fibonacci(n-2)\n\n# Driver code\nfibonacci(100)\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n354224848179261915075\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we have learned how to use the memoization technique in Python using function and class-based decorators. I hope you have well understood the things discussed above and are ready to use\/implement this memoization technique in your Python program to boost its speed.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we are going to discuss one of the very popular optimization techniques &#8211; Memoization in Python &#8211; primarily used to speed up computer programs. So, let&#8217;s get started! What is memoization in Python? In the world of computer programming, Memoisation or Memoization in Python is a special kind of optimization technique that [&hellip;]<\/p>\n","protected":false},"author":33,"featured_media":69055,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-21662","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/21662","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/33"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=21662"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/21662\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/69055"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=21662"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=21662"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=21662"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}