Send Close Add comments: (status displays here)
Got it!  This site "robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.  Note: This appears on each machine/browser from which this site is accessed.
Python: map, filter, reduce
by RS  admin@robinsnyder.com : 1024 x 640


1. Python: map, filter, reduce
Python has some functions from the functional world of programming that can help (be faster and more concise) when certain looping patterns are needed.

They rely on functions being first class objects.

2. Python map example
The Python map function allows a function to be mapped onto a list, returning an object that can be converted to a list. Here is an example.

Here is the Python code [#1]

Note the use of list to covert the map object into a list. Here is the output of the Python code.


3. Filter
The Python function filter can make it easy to filter a list. Here is an example.

Here is the Python code [#2]

Here is the output of the Python code.


4. Reduce
The Python reduce function, requiring the functools package, allows a list to be summarized as a single value. Here is an example. Here is the Python code [#3]

Here is the output of the Python code.


5. Powers of two
Here is a Python program to compute and output the powers of two from 0 to 8. You should understand each and every part of what is happening.

Here is the Python code [#4]

Here is the output of the Python code.


6. Notes
Note: One would not usually write such a construct as there are better ways to do this, but it shows how the reduce function works.

The reduce function works by using the first element of the list as the base case and all other list elements as the step cases. In the powers of two example, the base case needs to be the empty string. Then all other cases are the tuples representing the integer and the power of two of that integer. These are joined together using concatenation.

7. A better way
One way to do the above in a better way is as follows.

Here is the Python code [#5]

Here is the output of the Python code.




8. End of page

by RS  admin@robinsnyder.com : 1024 x 640