Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange reduce behaviour

Tags:

python

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?

like image 378
Fedor Kotov Avatar asked May 25 '11 12:05

Fedor Kotov


2 Answers

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.

like image 113
Wooble Avatar answered Nov 20 '22 13:11

Wooble


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]]
like image 7
phihag Avatar answered Nov 20 '22 13:11

phihag