This is the first part of the series on python built-in functions. In this tutorial we will present any() and all() built-ins. Both these functions serve to analyze the content of a sequence when applying a specific condition/requirement.

1. any(sequence)

any() function is used to check if at least one element of a sequence fulfills a given condition, i.e. returns “True”. Eg.:

 

>>> any ( [ True ] )
True
>>> any ( [ True, True, True ] )
True
>>> any ( [ True, True, False ] )
True
>>> z = [ 10, 20, 30 ]
>>> any ( [ x > 10 for x in z ] )
True
>>> any ( [ x > 50 for x in z ] )
False
>>>

In order to make a good use of this function you need to know the return value of different types in python. For example, all numbers except 0 return True:

>>> z = [ 0, 0, 0.01, 0 ]
>>> any ( z )
True
>>> z = [ 0, 0, 0, 0 ]
>>> any ( z )
False

Strings, apart the empty string, return True:

>>> any( [ 0, 0, "0", 0 ] )
True
>>> any ( [ 0, 0, "", 0 ] )
False

Empty sequences and None type are always False. Be careful! A sequence containing zeros, empty strings or other “False” types is not empty and consequently returns True:

>>> any ( [ [ ], ( ), { }, None, 0 ] )
False
>>> any ( [ [0], ( ), { }, None, 0 ] )
True
>>>

all(sequence)

all() function is used to check if all (!!!) elements of a sequence fulfill a given condition, i.e. return “True”. Eg.

 

>>> all ( [ True, True, True ] )
True
>>> all ( [ True, True, False ] )
False
>>> z = [ 10, 20, 30 ]
>>> all ( [ x>10 for x in z ] )
False
>>> all ( [ x>5 for x in z ] )
True
>>>

Like with any() examples above, be careful with empty/non empty sequences and remember that some types always return False:

>>> all ( [ " ", "0", [0], "None" ] ) # space is a character, the string is not empty
True
>>> all( [ "", "0", [0], "None" ] )
False
>>>

NB! An empty sequence returns True for all() and False for any():

>>> all ( [ ] )
True
>>> any ( [ ] )
False

That’s it 🙂

Please check out Part 2 of this tutorial where we take a closer look at type() and instanceof() functions. Till then!

The following two tabs change content below.