In Python, you might write ʻif x is y or ʻif x == y
.
At that time, you may get lost with ʻisand
==. Therefore, the differences between ʻis
and==
are summarized below.
--ʻIs compares objects (whether they are the same object) --
==` compares values (whether they are the same value)
x = <object A>
Is defined,
if x is <object A>:
This is the case when you want to write a conditional expression.
Of course, for True / False comparisons
x = True
Define,
if x is True:
Is not a mistake, but in this case pythonic
if x:
It is good to write.
→ The reason why x is True is okay is that the bool class True / False is designed so that there is always only one.
The values False and True will be singletons, like None.
Quote source PEP285
x = 1234
Is defined,
if x == 1234:
This is the case when you want to write a conditional expression.
Don't confuse is with ==, and use them properly.
Footnote 1 Contents presented in the comment section by @ 7of9
https://docs.python.org/3.6/library/functions.html#id
id(object) ... CPython implementation detail: This is the address of the object in memory.
Is the basis of the document.
Footnote 2 Contents presented in the comment section by @shiracamus
I checked the source of CPython. "is" was replaced with Is, Is was replaced with PyCmp_IS, and PyCmp_IS compared the addresses as follows:
Python/ceval.c
static PyObject *
cmp_outcome(int op, register PyObject *v, register PyObject *w)
{
int res = 0;
switch (op) {
case PyCmp_IS:
res = (v == w);
break;
case PyCmp_IS_NOT:
res = (v != w);
break;
In the end, we are doing address comparison.
Recommended Posts