Hey guys, I've looked over several Google results for basic explanations on

is / '=='

However, I don't think I quite understand enough to know what is the ideal operator for this.


if type(mylist) == list:
   print 'yes'

or do I use

if type(mylise) is list:
   print 'yes'

I understand superficially that == tests value and is test identifier (in the memory?) but not sure I really understand what is the best solution here.


Recommended Answers

All 6 Replies

IMHO the only time to use the keyword "is" is when you want to test that 2 objects point to the same block of memory, otherwise you can get unexpected results. This is a simple example of equal returning a True and is returning a False for the same comparison.

y = "a"
print "is", x is y, x, y     ## False
print "==", x==y, x, y       ## False

y += "bc"
print "\nis", x is y, x, y   ## False
print "==", x==y, x, y       ## True

I always use == in IF statements.

A little more about this. is is the identity comparison. == is the equality comparison.

With id() we can se memory loaction.
So here a and b point to same place in memory.

>>> a = 5
>>> b = 5
>>> a is b
>>> id(a)
>>> id(b)

Let`s try with list.

>>> a = []
>>> b = []
>>> a is b
>>> a == b
>>> id(a)
>>> id(b)

People often think that is is part of the comparison operator set.
The is statement does not compare two objects.

So a good rule is to not use is unless you want to check if something is None or something is not None.
The reason is works for things like "a is None" is because there is
only one None builtin in memory ever.

commented: good explanation +5

So basically "is" could be repaced with if id(a) == id(b)?

So basically "is" could be repaced with if id(a) == id(b)?

Exactly, because id(a) is nothing but the C pointer to object a converted to integer (see the function builtin_id in http://svn.python.org/view/python/trunk/Python/bltinmodule.c?revision=81029&view=markup) , and the is operator is implemented by comparing the pointer values (in http://svn.python.org/view/python/trunk/Python/ceval.c?view=markup)

static PyObject *
cmp_outcome(int op, register PyObject *v, register PyObject *w)
    int res = 0;
    switch (op) {
    case PyCmp_IS:
        res = (v == w);
    case PyCmp_IS_NOT:
        res = (v != w);
    v = res ? Py_True : Py_False;
    return v;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.