Skip to content

Commit 7c99fa5

Browse files
committed
Add some information on reduce! :D
It's a super useful function and usually falls right along these lines.
1 parent 83dcdc1 commit 7c99fa5

1 file changed

Lines changed: 29 additions & 3 deletions

File tree

map_filter.rst

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
Map & Filter
1+
Map, Filter and Reduce
22
------------
33

4-
These are two functions which facilitate a functional approach to
4+
These are three functions which facilitate a functional approach to
55
programming. We will discuss them one by one and understand their use
66
cases.
77

@@ -60,7 +60,7 @@ of a list of inputs we can even have a list of functions!
6060
Filter
6161
^^^^^^^^^
6262

63-
As the name suggests, filter creates a list of elements for which a
63+
As the name suggests, ``filter`` creates a list of elements for which a
6464
function returns true. Here is a short and concise example:
6565

6666
.. code:: python
@@ -75,3 +75,29 @@ The filter resembles a for loop but it is a builtin function and faster.
7575

7676
**Note:** If map & filter do not appear beautiful to you then you can
7777
read about ``list/dict/tuple`` comprehensions.
78+
79+
Reduce
80+
^^^^^^^^^
81+
82+
``Reduce`` is a really useful function for performing some computation on
83+
a list and returning the result. For example, if you wanted to compute
84+
the product of a list of integers.
85+
86+
So the normal way you might go about doing this task in python us using
87+
a basic for loop.
88+
89+
.. code:: python
90+
product = 1
91+
list = [1, 2, 3, 4]
92+
for num in list:
93+
product = product * list
94+
95+
# product = 24
96+
97+
Now let's try it with reduce.
98+
.. code:: python
99+
100+
from functools import reduce
101+
product = reduce( (lambda x, y: x * y), [1, 2, 3, 4] )
102+
103+
# Output: 24

0 commit comments

Comments
 (0)