[Tutor] Truth value testing in if, while and boolean operations

Mats Wichmann mats at wichmann.us
Thu Oct 15 11:42:21 EDT 2020


On 10/15/20 9:33 AM, Manprit Singh wrote:
> Dear sir ,
> 
> While referring to python docs , i found that under the heading "Truth
> Value testing" it is written that
> 
> empty sequences and collections: '', (), [], {}, set(), range(0) are
> considered as false .
> 
> In PEP8 docs under "programming recommendations" it is written that :
> 
> "For sequences, (strings, lists, tuples), use the fact that empty sequences
> are false:
> 
> so it is a valid practice to write like this
> 
> if sequence:        # do_this() will be executed if sequence is not empty
> 
>     do_this()
> 
> else:              # do_this_1() will be executed if sequence is  empty
> 
>     do_this_1()
> 
> There is nothing mentioned in PEP 8 about using the sets, dicts etc in the
> same way as given above . As we know that empty sets & dicts are also
> considered false, using dicts and sets in the way as given above is valid
> and adheres to PEP 8 guidelines ?

As long as you don't use the actual words dict and set (except as
callables, to create new objects)  since those are builtins and will
return true because in this context they are non-empty objects.



> if dict:          # do_this() will be executed if dict is not empty
> 
>     do_this()
> 
> else:             # do_this_1() will be executed if dict is  empty
> 
>     do_this_1()
> 
> _____________________________________________________________________
> 
> if set:           # do_this() will be executed if set is not empty
> 
>     do_this()
> 
> else:              # do_this_1() will be executed if set is  empty
> 
>     do_this_1()



>>> bool({})
False
>>> bool(dict())
False
>>> bool(dict)
True
>>> bool(set)
True
>>> bool(set())
False
>>>



More information about the Tutor mailing list