Python Functools lru_cache() (original) (raw)

Last Updated : 11 Jun, 2026

lru_cache() function from Python's functools module is used to cache the results of function calls. When the same function is called again with the same arguments, the stored result is returned instead of executing the function again.

**Example: The following example caches the result of a function call so that repeated calls with the same argument reuse the stored result.

Python `

from functools import lru_cache

@lru_cache() def square(n): print("Calculating...") return n * n

print(square(5)) print(square(5))

`

Output

Calculating... 25 25

**Explanation:

Syntax

@lru_cache(maxsize=128, typed=False)

**Parameters:

Examples

**Example 1: The Fibonacci sequence contains many repeated calculations. Using lru_cache() stores previously computed values and avoids recalculating them.

Python `

from functools import lru_cache

@lru_cache() def fib(n): if n < 2: return n return fib(n - 1) + fib(n - 2)

print(fib(30))

`

**Explanation:

**Example 2: This example caches the vowel count for previously processed strings.

Python `

from functools import lru_cache

@lru_cache(maxsize=100) def count_vowels(s): s = s.lower() return sum(s.count(v) for v in "aeiou")

print(count_vowels("Welcome to GeeksforGeeks")) print(count_vowels("Welcome to GeeksforGeeks"))

`

**Explanation:

**Example 3: This example uses lru_cache() to store factorial values computed through recursion.

Python `

from functools import lru_cache

@lru_cache() def fact(n): if n <= 1: return 1 return n * fact(n - 1)

print(fact(6))

`

**Explanation: