Search code examples
pythontuplesinterpreterpythoninterpreter

Does python cache items in the same line and use again later


With this line:

print(sum(tuple), len(tuple), sum(tuple)/len(tuple))

Will python cache sum(tuple) in the 0 index and use it in the average calculation (2 index)?

Or will with calculate sum(tuple) again?


Solution

  • Python won't perform this optimization for you. You can see this by defining your own function instead of sum and observing the side effect:

    import functools
    
    def my_sum(x):
        print('my sum')
        return functools.reduce(lambda a, b: a + b, x)
    
    tup = (1, 2, 3)
    print(my_sum(tup), len(tup), my_sum(tup)/len(tup))
    

    If you run this snippet, you'll see the phrase "my sum" printed twice, proving the call to my_sum isn't optimized out.

    Having said that, you could implement this optimization yourself by using functools' cache:

    import functools
    
    @functools.cache
    def my_sum(x):
        print('my sum')
        return functools.reduce(lambda a, b: a + b, x)
    
    tup = (1, 2, 3)
    print(my_sum(tup), len(tup), my_sum(tup)/len(tup))
    

    (or by using the := operator as Andrej Kesely suggests in the comments)