Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22852

Python Morsels: Avoid "reduce" in Python

$
0
0

Python's reduce function can "reduce" an iterable to a single value. But the reduce function is often more hassle than it's worth.

What is the functools.reduce function?

The functools.reduce function looks a little bit like this:

not_seen=object()defreduce(function,iterable,default=not_seen):"""An approximation of the code for functools.reduce."""value=defaultforiteminiterable:ifvalueisnot_seen:value=itemcontinuevalue=function(value,item)returnvalue
not_seen=object()defreduce(function,iterable,default=not_seen):"""An approximation of the code for functools.reduce."""value=defaultforiteminiterable:ifvalueisnot_seen:value=itemcontinuevalue=function(value,item)returnvalue

The reduce function is a bit complex. It's best understood with an example.

Performing arithmetic (a bad example)

>>> fromfunctoolsimportreduce …

Read the full article: https://www.pythonmorsels.com/reduce/


Viewing all articles
Browse latest Browse all 22852

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>