Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python operator, no operator for "not in"

This is a possibly silly question, but looking at the mapping of operators to functions I noticed that there is no function to express the not in operator. At first I thought this was probably because the interpreter just reorders this to be not x in y, but there is a function for is not which seems like it should behave exactly the same as not in. Am I missing something, or does that operator really not exist?

Here's a really stupid example where you might want this:

def compare_iter(a,b,func):
    return [func(aa,bb) for aa,bb in zip(a,b)]

my_compare=compare_iter(xx,yy,lambda x,y:x not in y)  #lambda -- yuck
my_compare=map(operator.not_,compare_iter(xx,yy,operator.contains)  #extra map?  grr...
#it would be nice to do: my_compare=compare_iter(xx,yy,operator.not_contains)

Of course I could write my own function for this, but then you pay a price in efficiency whereas the operator module could push this code out of python and therefore execute faster.

like image 864
mgilson Avatar asked Jul 11 '12 14:07

mgilson


People also ask

How do you say not in Python?

You can use "!= " and "is not" for not equal operation in Python. The python != ( not equal operator ) return True, if the values of the two Python operands given on each side of the operator are not equal, otherwise false .

Is not VS != In Python?

The != operator compares the value or equality of two objects, whereas the Python is not operator checks whether two variables point to the same object in memory.

What is the use of <> in Python?

or <> . Both stands for not equal. [Reference: Python language reference] The comparison operators <> and != are alternate spellings of the same operator. !=


1 Answers

Another function is not necessary here. not in is the inverse of in, so you have the following mappings:

obj in seq => contains(seq, obj)

obj not in seq => not contains(seq, obj)

You are right this is not consistent with is/is not, since identity tests should be symmetrical. This might be a design artifact.

like image 161
Frédéric Hamidi Avatar answered Oct 15 '22 04:10

Frédéric Hamidi