Search code examples
pythontypeerrorreducehigher-order-functionsiterable

Unexpected TypeError when using reduce function


Here is the line of code:

product = list(reduce(lambda a, b: a*b, [2,2,2,2,2]))

Error:

TypeError: 'int' object is not iterable


Solution

  • if you want to put your result in a list, you can use this code:

    import functools
    product = [functools.reduce((lambda x,y:x*y),[2,2,2,2,2])]
    print(product)
    

    The list function cannot be used because it corresponds to a type conversion which is not possible as your result is an integer.