-1

I'm trying use python's reduce in a similar way to racket's foldl, but when I run the following code:

functools.reduce(lambda x, y: x.append(y), [1,2,3], [])
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'append'

Can you please help explain the error and suggest a fix?

4
  • 1
    reduce expects a function argument that returns something, which append doesn't... Commented Mar 10, 2015 at 22:05
  • What's the end goal here? There seem to be multiple things you're confused about, so I'm not sure where to start. What does "racket's foldl" do? (I'm not familiar with Racket.) Are you aware that .append() is an in-place operation, so always returns None? And are you aware that you don't have another reference to this list, so even if you did .append() to it, the changes would be lost? Why are you breaking up [1,2,3] into elements instead of doing them all at once with .extend([1,2,3])? Why are you using an empty list in the first place when you could just use [1,2,3]? Commented Aug 11 at 16:35
  • Please also write a better title, ideally phrased as a question. See How to Ask for tips. Commented Aug 11 at 16:43
  • What do you mean by "initializer"? I can't see any __init__ method being called here, if that's what you mean. functools.reduce isn't a class, if that's what you thought; it's just a function. Commented Aug 11 at 16:46

1 Answer 1

5

That's because append() doesn't return anything.

You can do:

functools.reduce(lambda x, y: x + [y], [1,2,3], [])
Sign up to request clarification or add additional context in comments.

3 Comments

thank you so much! My array has tuples where the 2nd value is an integer that I want to add. I JUST couldn't figure out why functools.reduce((lambda x, y: x[1]+y[1]), arr) wasn't working like it did in python 2.7. Finally, this worked - functools.reduce((lambda x, y: x+y[1]), arr, 0)
This does work, but it's absolutely not idiomatic. There's no need to break up [1,2,3] into elements when you could just do [] + [1,2,3]. And then there's no need to use an empty list at all, just use [1,2,3]. That said, it's certainly possible OP's example doesn't exactly represent their real code, but this should at least be mentioned.
@Meghna In your case, use sum(t[1] for t in arr). See my comment above for context. sum() works like reduce(lambda x, y: x+y, ..., 0).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.