When I execute this code in python 2.6
reduce(lambda x,y: x+[y], [1,2,3],[])
I get [1, 2, 3] as expected. But when I execute this one (I think it is equivalent to previous)
reduce(lambda x,y: x.append(y), [1,2,3],[])
I get an error message
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'append'
Why these two lines of code do not give the same result?
x.append(y)
is not equivalent to x+[y]
; append
modifies a list in place and returns nothing, while x+[y]
is an expression that returns the result.
reduce
calls the function and uses the return value as the new result. append
returns None
, and therefore the next append
invocation fails. You could write
def tmpf(x,y):
x.append(y)
return x
reduce(tmpf, [1,2,3], [])
and get the correct result. However, if the result is a list of the same size as the input, you're not looking for reduce: The result of reduce should usually be a single value. Instead, use map or simply
[x for x in [1,2,3]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With