Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'is' operator do in Python?

I was (maybe wrongfully) thinking that is operator is doing id() comparison.

>>> x = 10
>>> y = 10
>>> id(x)
1815480092
>>> id(y)
1815480092
>>> x is y
True

However, with val is not None, it seems like that it's not that simple.

>>> id(not None)
2001680
>>> id(None)
2053536
>>> val = 10
>>> id(val)
1815480092
>>> val is not None
True

Then, what does 'is' operator do? Is it just object id comparison just I conjectured? If so, val is not None is interpreted in Python as not (val is None)?

like image 623
prosseek Avatar asked Aug 16 '13 14:08

prosseek


People also ask

What is the use of IS operator in Python?

The is keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object.

What is the difference between == & is?

== is for value equality. It's used to know if two objects have the same value. is is for reference equality. It's used to know if two references refer (or point) to the same object, i.e if they're identical.

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

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

Is or a Python operator?

Boolean or logical operators are AND (logical AND or conjunction), OR (logical OR or disjunction), and NOT (logical NOT or negation). The keywords and , or , and not are the Python operators for these operations.


1 Answers

You missed that is not is an operator too.

Without is, the regular not operator returns a boolean:

>>> not None
True

not None is thus the inverse boolean 'value' of None. In a boolean context None is false:

>>> bool(None)
False

so not None is boolean True.

Both None and True are objects too, and both have a memory address (the value id() returns for the CPython implementation of Python):

>>> id(True)
4440103488
>>> id(not None)
4440103488
>>> id(None)
4440184448

is tests if two references are pointing to the same object; if something is the same object, it'll have the same id() as well. is returns a boolean value, True or False.

is not is the inverse of the is operator. It is the equivalent of not (op1 is op2), in one operator. It should not be read as op1 is (not op2) here:

>>> 1 is not None     # is 1 a different object from None?
True
>>> 1 is (not None)   # is 1 the same object as True?
False
like image 176
Martijn Pieters Avatar answered Sep 27 '22 16:09

Martijn Pieters