I would expect the two to mean the same, from a functional equational standpoint, however:
x = [1, 2, 3]
y = ['a', 'b', 'c']
reduce(lambda x, y: x + y, zip(x, y)) # works
sum(zip(x, y)) # fails
Why is sum
failing here?
I would expect the two to mean the same, from a functional equational standpoint, however:
x = [1, 2, 3]
y = ['a', 'b', 'c']
reduce(lambda x, y: x + y, zip(x, y)) # works
sum(zip(x, y)) # fails
Why is sum
failing here?
Copyright © 2021 Jogjafile Inc.
The actual problem is, with the
sum
's default start value. Quoting the documentation,But, in case of
reduce
, if no optional start value is given, it will use the first value in the iterable as the initializer. So,reduce
is actually evaluating it like thisSince
sum
assumes start value as 0, it evaluates it like this,In this case, it tries to add
0
with a tuple and that is why you are gettingTo fix this, pass an empty tuple, to
sum
's start, like thisNow, with the initial value being an empty tuple, the evaluation happens like this
Note: In both these case, there will be more than one intermediate tuples created. To avoid that, I would recommend flattening the data and pass it to
tuple
constructor as a generator expression, like this