Interesting list Validity (True/False)

Carsten Haese carsten at uniqsys.com
Fri May 11 17:07:22 EDT 2007


On Fri, 2007-05-11 at 12:28 -0700, nufuhsus at gmail.com wrote:
> Hello all,
> 
> First let me appologise if this has been answered but I could not find
> an acurate answer to this interesting problem.
> 
> If the following is true:
>     C:\Python25\rg.py>python
>     Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32
> bit (Intel)] on
>     win32
>     Type "help", "copyright", "credits" or "license" for more
> information.
>     >>> [] == []
>     True
>     >>> ['-o'] == []
>     False
>     >>> ['-o'] == False
>     False
>     >>>

Your confusion stems from the fact that for a given object, the answer
to the following three questions can be vastly different:
a) Is the object identical to True?
b) Is the object equal to True?
c) Is the object considered to be True in an "if" statement?

Observe:

>>> def check_trueness(obj):
...    if obj is True: print repr(obj), "is identical to True."
...    else: print repr(obj), "is not identical to True."
...    if obj == True: print repr(obj), "is equal to True."
...    else: print repr(obj), "is not equal to True."
...    if obj: print repr(obj), "is considered to be True by if."
...    else: print repr(obj), "is not considered to be True by if."
...
>>> check_trueness(True)
True is identical to True.
True is equal to True.
True is considered to be True by if.
>>> check_trueness(1)
1 is not identical to True.
1 is equal to True.
1 is considered to be True by if.
>>> check_trueness([1])
[1] is not identical to True.
[1] is not equal to True.
[1] is considered to be True by if.
>>> check_trueness([])
[] is not identical to True.
[] is not equal to True.
[] is not considered to be True by if.

Testing whether an object is equal to True is a much stronger test than
whether it is considered to be True in an 'if' statement, and the test
for identity is stronger still. Testing whether an object is equal to
True or identical to True is useless in most Python programs.

So, rather than doing this:

if thing==True:
   # blah

Just do this:

if thing:
   # blah

Hope this helps,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list