All, any, and reduce in python

Not too long ago, at work, a discussion was conjured over the uses of all, any, reduce in python. These are standard built-in python functions that can be a time saver in certain situations. All of these are similar in the sense that they:

  1. Return an object (everything in python is an object)
  2. Can evaluate an iterable based on operators like OR/AND
  3. Can be used to produce cleaner, more readable code
  4. May be efficient when large amounts of data need to be evaluated

Let’s look at the following code:

a = True
b = False
c = True
d = True  

# long winded approach
if a and b and c and d:
    print 'All true'  

# using all
if all([a,b,c,d]):
    print 'All true'  

# using reduce
from operator import and_
if reduce(and_,[a,b,c,d]):
    print 'All true'

Your results for each of the snippets above should be None because b = False. Here is the same example using the OR expression:

a = True
b = False
c = True
d = True  

# long winded approach
if a or b or c or d:
    print 'One was true'  

# using any
if any([a,b,c,d]):
    print 'One was true'  

# using reduce
from operator import and_
if reduce(and_,[a,b,c,d]):
    print 'One was true'

The result in all the cases will print ‘One was true’.

Reduce gives you a little more flexibility. It can be used to add/subtract numbers in an iterable, evaluate with AND/OR, or a more practicle use could be to combine filter criteria in a Django query. For example:

from operator import or_
from django.db.models import Q
from models import Poll

kwargs = [{'question':'test1'},{'question':'test2'}]
query_objects = []

for kwarg in kwargs:
    query_objects += [Q(**kwarg)]

if query_objects:
    query = reduce(operator.or_,query_objects)
    polls = Poll.objects.filter(query)

Another use case for (any) could be to check if a certain parameter exists in a query string like so:

query_string = '&a=1&b=2&c=3'

if any(map(query_string.find,['a','b'])):
    print 'It exists!'

In most cases “Readability counts“. If using any, all, map, and reduce causes your code to be overly complex when it should be simple avoid using them. Use them out of necessity.

Speak Your Mind

*


*

Fork me on GitHub