Python any() and Python bool() built-in functions

Here let’s discuss the Python any() and bool() built-in functions.

i)any()
ii)bool()


Python any()

The Python any() function return True if any of the elements of the iterable pass to any() is True.If the iterable is empty any() returns False.

Any non-zero value is considered to be True.So if all the elements of the iterable is 0 then any() will definitely return Fasle since there are no True element.

Link : Python all()

By iterable we are referring to the data type such as list,tuple,set dictionary ,string,etc.

A code example is shown below.

>>> #Passing list
>>> any( [] ) #Passing empty list
False
>>> any( [23 ,78 , 'C++ still rocks'] )
True
>>> any( [23 , 0 , 'Python 0)'] )
True
>>> any( [0 , 0, 0, 0,] ) #No True element
False
>>> any( [1 ,0 , 0, 0]) #One True element
True
>>> #Passing string
>>> any( '' ) #Empty string
False
>>> any( '0' )
True
>>> #Pasing dictionary
>>> any( {} ) #Empty dictionary
False
>>> any( {0:'New'  , 23:'Twenty-three'} )
True
>>> any( {0:'Zero-1' , 0:'Zero-2'}  )
False
>>> any( {23:0 , 90:0} )
True

In case of dictionary the element is considered False when the key is 0 and when all the keys are 0 any() return False (Line 22 in the above example)

Link :Python list



Python bool()

The Python bool() returns either True or False value for any value.But which value are considered as false and which True?

Any built-in objects are considered True if the len() function returns non-zero value.Most of the built-in objects considered False are:
 
•constants defined to be false: None and False.
 
•zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
 
•empty sequences and collections: ”, (), [], {}, set(), range(0)

Link :Python set

Consider the code below.

>>> bool( 0 )
False
>>> bool( 0.09)
True
>>> bool( '' ) #empty string
False
>>> bool( [] ) #Empty list
False
>>> bool( {} ) #Empty dictionary
False
>>> st=set() #Empty set
>>> bool( st )
False
>>> bool( [23, 89] )	    
True

Testing out bool() functions with Decimal and Fraction and range().


Link : Python Decimal

Link : Pyhton Fraction

Link : Python range()

>>> #Testing Decimal 
>>> from decimal import Decimal as D
bool( D(34) )
True
>>> bool( D(0.0) )
False
>>> #Testing Fraction
>>> from fractions import Fraction
>>> bool( Fraction( 0,9) )
False
>>> bool( Fraction(9, 1) )   
True
>>> #Testing range()
>>> bool( range(0))
False
>>> bool(range(34))   
True
>>> bool( range(-2))	    
False

The range() with -ve argument also gives False.


*Side note

The bool class is a subclass of int.It cannot be subclassed further.Its only instances are False and True.




Leave a Reply

Your email address will not be published. Required fields are marked *