Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Python2's built-in reduce and functools.reduce different?

Both have exact same documentation, and it seems to me that both stem from same source code in https://hg.python.org/cpython/file/Modules/_functoolsmodule.c.

However, I am not sure about it. I didn't find any other refernces in the source code of CPython. Can some one shed some more light on this here?

like image 338
oz123 Avatar asked May 01 '16 21:05

oz123


People also ask

What is Functools reduce?

The reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. This function is defined in “functools” module. Working : At first step, first two elements of sequence are picked and the result is obtained.

Why was reduce moved to Functools?

Python's reduce() was originally a built-in function (and still is in Python 2. x), but it was moved to functools. reduce() in Python 3.0. This decision was based on some possible performance and readability issues.

What is Functools?

The functools module, part of Python's standard Library, provides useful features that make it easier to work with high order functions (a function that returns a function or takes another function as an argument ).

What is the difference between reduce and map in Python?

reduce() works differently than map() and filter() . It does not return a new list based on the function and iterable we've passed. Instead, it returns a single value. Also, in Python 3 reduce() isn't a built-in function anymore, and it can be found in the functools module.


1 Answers

Per the documentation of functools.reduce in Python 2:

This is the same function as reduce(). It is made available in this module to allow writing code more forward-compatible with Python 3.

like image 82
Binary Birch Tree Avatar answered Oct 05 '22 16:10

Binary Birch Tree