The "float" object is not iterable when applying sum + sum in python2

I want to apply reduce(sum, iterable)floating point numbers to a list flist = [0.2, 0.06, 0.1, 0.05, 0.04, 0.3].

print list(reduce(sum, flist)) is returning TypeError: 'float' object is not iterable

Why when flistIS is iterable?

+4
source share
2 answers

The real problem is with the function sum. It takes only iterable, not two separate values. For instance,

>>> sum(1, 2)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> sum([1, 2])
3

So you cannot use sumhere, instead you can use a custom lambda function or operator.add, like this

>>> from operator import add
>>> reduce(add, flist, 0.0)
0.75
>>> reduce(lambda a, b: a + b, flist, 0.0)
0.75

.. reduce BDFL . , reduce functools Python 3.x.

+4

, flist:

reduce(lambda x,y: x+y,flist)

0.75.

,

sum(flist)
+1

All Articles