0

I'm wondering why this evaluates to True.

x = 1
if x is 1:
    print "Does x and 1 point to the same object?"
    print "Does this mean python doesn't store redundant values?"

It doesn't work for this case as I expect.

x = range(10)
y = range(10)
if not x is y:
    print "I expect this"

My understanding is that is checks to see if two names are pointing to the same object. Does this imply that python has a mechanism to avoid creating redundant values?

Matt
  • 3,592
  • 5
  • 21
  • 26
  • 2
    Between -5 and 256, yes, they are literally the same object depending on the implementation of Python – Cory Kramer Jun 29 '15 at 18:16
  • 1
    You shouldn't rely on the result of `is`. It is perfectly reasonable for python to optimize *immutable* built-in types. `is` is the **only** operator that affects the result, so this doesn't really break much. However this is done only for a few types because most of the objects created by a program fall into specific categories that should be optimized (e.g. integers, lists, dictionaries). – Bakuriu Jun 29 '15 at 18:18

1 Answers1

2

This is an implementation detail of the CPython interpreter, but integers with small values are "interned" -- whenever the result of an expression falls within a certain range, an existing int object with the same value is returned.

You could check the range that gets interned by using the following code:

interned_range = [i for i in range(-1000, 1000) if i+0 is i]
print min(interned_range), max(interned_range)

My CPython inters integers between -5 and 256 inclusive.

Being an implementation detail, this behaviour should generally not be relied upon.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • in CPython 3.7, why does `max(interned_range)` returns a `TypeError: 'str' object is not callable`? – deadvoid Oct 12 '18 at 12:43