Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Difference between != and "is not"

I'm unclear about the difference between the syntax != and is not. They appear to do the same thing:

>>> s = 'a'
>>> s != 'a'
False
>>> s is not 'a'
False

But, when I use is not in a list comprehension, it produces a different result than if I use !=.

>>> s = "hello"
>>> [c for c in s if c is not 'o']
['h', 'e', 'l', 'l', 'o']
>>> [c for c in s if c != 'o']
['h', 'e', 'l', 'l']

Why did the o get included in the first list, but not the second list?

like image 389
Channel72 Avatar asked Apr 25 '11 19:04

Channel72


People also ask

Why do we use != In Python?

Not Equal Operator in Python If the values compared are equal, then a value of true is returned. If the values compared are not equal, then a value of false is returned. != is the symbol we use for the not equal operator.

What is the difference between != and == in Python?

The = is a simple assignment operator. It assigns values from right side operands to the left side operand. While on the other hand == checks if the values of two operands are equal or not. If yes, the condition becomes true and it returns a non zero value.

What is the opposite of != In Python?

You can use the not equal Python operator for formatted strings (f-strings), introduced in Python 3.6. To return an opposite boolean value, use the equal operator ==. Keep in mind that some fonts change != to look like ≠ !

Is != The same as ==?

The equal-to operator ( == ) returns true if both operands have the same value; otherwise, it returns false . The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .


2 Answers

is tests for object identity, but == tests for object value equality:

In [1]: a = 3424
In [2]: b = 3424

In [3]: a is b
Out[3]: False

In [4]: a == b
Out[4]: True
like image 109
tkerwin Avatar answered Sep 20 '22 00:09

tkerwin


is not compares references. == compares values

like image 45
c1de0x Avatar answered Sep 19 '22 00:09

c1de0x