Skip to content
Back to posts

Understanding is in Python

A guide to Python object identity, the is operator, and the implementation details that can make immutable objects share identities.

Every Python object has three essential properties: identity, type, and value.

The identity uniquely identifies an object. The is operator compares two objects by that identity.

None is None
# True
a = 1; b = 1
a is b
# True
a = "myX"; b = "myX";
a is b
# True
a = 1.8; b = 1.8
a is b
# False
a = 3L; b = 3L
a is b
# False
a = 1+2j; b = 1+2j
a is b
# False
a = (1, 2); b = (1, 2)
a is b
# False
a = [1, 2]; b = [1, 2]
a is b
# False
a = {"male":1}; b = {"male": 1}
a is b
# False

Full example on GitHub Gist.

Everything in Python is an object. Strings and integers are immutable objects; strings may be stored in a string intern pool, while integers may be stored in a small-integer pool. In the example above, both a and b can point to the same memory used by "myX", so their identities match and a is b is True.

Large integers are not necessarily shared. On my 64-bit Ubuntu machine, the largest integer for which this identity comparison held was 256; with 257, it returned False.


Originally published on SegmentFault.

Copyright notice

Unless otherwise stated, quietin owns the copyright in all articles. All rights reserved. Except as permitted by law or with prior written permission, reproduction or republication, in whole or in part, is prohibited. Permitted quotations must credit the author and link to the original article.