Python reduce explanation
It's easier if you break out the lambda
into a function, so it's clearer to what's going on:
>>> def do_and_print(t1, t2):
print 't1 is', t1
print 't2 is', t2
return t1+t2
>>> reduce(do_and_print, ((1,2), (3,4), (5,)))
t1 is (1, 2)
t2 is (3, 4)
t1 is (1, 2, 3, 4)
t2 is (5,)
(1, 2, 3, 4, 5)
reduce()
applies a function sequentially, chaining the elements of a sequence:
reduce(f, [a,b,c,d], s)
is the same as
f(f(f(f(s, a), b), c), d)
and so on. In your case the f()
is a lambda function (lambda t1, t2: t1 + t2
) which just adds up its two arguments, so you end up with
(((s + a) + b) + c) + d
and because the parenthesizing on adding sequences doesn't make any difference, this is
s + a + b + c + d
or with your actual values
(1, 2) + (3, 4) + (5,)
If s
is not given, the first term is just not done, but usually the neutral element is used for s
, so in your case ()
would have been correct:
reduce(lambda t1, t2: t1 + t2, lot, ())
But without it, you only run into trouble if lot
has no elements (TypeError: reduce() of empty sequence with no initial value
).