Operator Precedence/Boolean Logic

Antoon Pardon antoon.pardon at rece.vub.ac.be
Thu Jun 23 06:54:55 EDT 2016


Op 23-06-16 om 11:53 schreef Marko Rauhamaa:
> Antoon Pardon <antoon.pardon at rece.vub.ac.be>:
>
>> Op 23-06-16 om 11:10 schreef Marko Rauhamaa:
>>> The __len__ method is not guaranteed to execute in O(1). See:
>>>
>>>    <URL: https://docs.python.org/3/reference/datamodel.html?highlig
>>>    ht=__len__#object.__len__>
>> As far as I can see, neither is the __bool__ method.
> Correct, but in the absence of an __empty__ method, __bool__ gives the
> class the best opportunity to check for emptiness quickly.
>
> This is not only a theoretical concern. It's quite common for data
> structures not to maintain an element count because it's extra baggage
> that's not always needed and any application could keep a track of.
> However, an emptiness check is often trivial.

Maybe something like this:

def empty(sq):
    try:
        iter(sq).next()
    except StopIteration:
        return False
    except:
        raise TypeError
    else:
        return True



More information about the Python-list mailing list