Hacker News new | past | comments | ask | show | jobs | submit login

That example works only because the function sum is already defined in Python. If you wanted to do something less common than summing up elements you would have to either use reduce or implement a for loop.



In Python 3, reduce was intentionally moved into the functools library because it was argued that its two biggest use cases by far were sum and product, which were both added as builtins. In my experience, this has very much been the case. Reduce is still there if you need it, and isn't any more verbose. The only thing that is a little bit more gross about this example is the lambda syntax; I would argue that even that is a moot point, however, since Python supports first-class functions, so you can always just write your complicated reduce function out and then plug it in.


True, but I've used python a lot, and I've used reduce maybe...twice? (well, twice that I can find on my github at least)


I just counted the number of reduce I used in my current python project (6k lines). reduce comes up 32 times. And by comparison, map is used 159 times and filter 125 times - for some reason I tend to use list comprehensions less than I should.


I also thing you use map not a ton if you get the list comprehension syntax down... it is a map with less cruft mostly...


curious how often reduce is used with something else than operator.add?


One occurence was to calculate the GCD of a list of polynomials.

In fact I had "reduce" appearing in the names of some of my variables so I used it less than 32 times, about 20 times in that project.


I see nothing particularly inspiring in the examples posted on http://stackoverflow.com/questions/15995/useful-code-which-u...

Could you show your reduce calls?


They are very similar to this one from your link: http://stackoverflow.com/questions/15995/useful-code-which-u...


Well, or write a static method somewhere that you call. Sum is used a lot, so handy it is written somewhere (vs having to do a lambda x + x thing.


That seems like an argument against lambda functions in general - why use lambdas when you can define a static function for every case? Well, the answer in my opinion is because it makes code more readable if you can define a simple lambda function instead of having to name every single function in the code base.


Well if you are going to reuse the function, name it. If it is a 1 time thing, use a lambda.


Sounds great in theory. Problem is if you need a lambda that isn't a single expression, you then have to name it. Welcome to the conversation.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: