Usefulness of the "not in" operator

DevPlayer devplayer at gmail.com
Sat Oct 15 18:04:24 EDT 2011


On Oct 8, 8:41 am, Alain Ketterlin <al... at dpt-info.u-strasbg.fr>
wrote:
> candide <cand... at free.invalid> writes:
> > Python provides
>
> >     -- the not operator, meaning logical negation
> >     -- the in operator, meaning membership
>
> > On the other hand, Python provides the not in operator meaning
> > non-membership. However, it seems we can reformulate any "not in"
> > expression using only "not" and "in" operation.
>
> Sure, but note that you can also reformulate != using not and ==, <
> using not and >=, etc. Operators like "not in" and "is not" should
> really be considered single tokens, even though they seem to use "not".
> And I think they are really convenient.
>
> -- Alain.

1. I thought "x not in y" was later added as syntax sugar for "not x
in y"
meaning they used the same set of tokens. (Too lazy to check the
actual tokens)

2. "x not in y" ==>> (True if y.__call__(x) else False)
class Y(object):
    def __contains__(self, x):
        for item in y:
        if x == y:
            return True
        return False

And if you wanted "x not in y" to be a different token you'd have to
ADD

class Y(object):
    def __not_contained__(self, x):
        for item in self:
            if x == y:
                return False
        return True

AND with __not_contained__() you'd always have to iterate the entire
sequence to make sure even the last item doesn't match.

SO with one token "x not in y" you DON'T have to itterate through the
entire sequence thus it is more effiecient.



More information about the Python-list mailing list