Search code examples
pythonreducefunctools

Why is reduce returning a list instead of a single value?


I was just exploring reduce, but I'm not understanding the whole systematic behind it. I do understand that reduce will most likely return a single value, but how does it work in this context?

    answer = reduce(lambda x, y: x[0]*x[1] * ([y[0] + y[1]]), [(2,6), (1, 2), (5, 6)])

Solution

  • [y[0] + y[1]] is a list, so your lambda is multiplying an integer x[0]*x[1] by a list ([y[0] + y[1]]), so you're getting another list as the result because:

    >>> 5 * [6]
    [6, 6, 6, 6, 6]
    >>> 8 * [4,6]
    [4, 6, 4, 6, 4, 6, 4, 6, 4, 6, 4, 6, 4, 6, 4, 6]
    

    As for why the result is 9 * [11]:

    >>> def thing(x, y):
    ...  print(x, y)
    ...  return x[0]*x[1] * ([y[0] + y[1]])
    ... 
    >>> reduce(thing, [(2,6), (1, 2), (5, 6)])
    1. (2, 6) (1, 2)
    2. [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] (5, 6)
    [11, 11, 11, 11, 11, 11, 11, 11, 11]
    
    1. x == (2, 6), y == (1, 2) => tmp1 == (2 * 6) * [1 + 2] == 12 * [3]
    2. The first argument is the accumulator, so x is now the list of 3's from the previous iteration. Per your formula, result == (3 * 3) * [5 + 6] == 9 * [11]