Editor

Fix the Caching Bug

Advanced · Fix the bug · from Python functools: lru_cache, partial, reduce, singledispatch

From the lesson: Python functools: lru_cache, partial, reduce, singledispatch

Imagine your functions could remember past answers, come pre-loaded with some arguments, or automatically handle different data types. That's what the functools module gives you: power-ups for your functions.

Read the lesson

This code tries to cache an add function, but it passes a list as an argument, which is not hashable. Fix it by converting the list to a tuple before passing it to the cached function.

Expected output: 6

from functools import lru_cache
@lru_cache(maxsize=None)
def sum_items(items):
return sum(items)
numbers = [1, 2, 3]
print(sum_items(numbers)) # This crashes!

More functools exercises

All Python exercises · 50 practice problems · Standard Library Essentials quiz