1

I run below python code, a and b will point to the same object as I know.

>>> a=10
>>> b=10
>>> a is b
True

but when I change the 10 to a bigger number such as 100000, the result is weird.

>>> a=100000
>>> b=100000
>>> a is b
False

It seems that python create two 100000 in memory.

Then I try below code:

>>> lst=[10,10]
>>> lst[0] is lst[1]
True

>>> lst=[100000 ,100000 ]
>>> lst[0] is lst[1]
True

In list the numbers (10 or 100000) are both in same object.

That's what I confused. Why when the number is bigger, Python create two object? and why in List, it still use one copy?

Holloway
  • 6,412
  • 1
  • 26
  • 33
roast_soul
  • 3,554
  • 7
  • 36
  • 73
  • python 3.4.2 - I don't see that behavior. – Jon Surrell Feb 24 '15 at 15:13
  • @JonSurrell: I do. But that's because Python also stores literals as constants. – Martijn Pieters Feb 24 '15 at 15:14
  • 1
    Bottom line: Python optimises stuff. Loads of stuff. And those optimisations can lead to Python storing just one copy of stuff. Including small integers and literals used in code. *Don't count on this behaviour in your code*, as optimisations are not part of the language definition. – Martijn Pieters Feb 24 '15 at 15:15
  • Scratch that, I __do__ see it in Python3.4.2 interpreter. __Not__ in Python 3.4.2 + IPython 2.3.0 – Jon Surrell Feb 24 '15 at 15:15
  • 1
    `import dis; print(compile('[100000, 100000]', 'stdin', 'eval').co_consts)` produces `(100000,)`, meaning Python stored just the one integer to run the code with. – Martijn Pieters Feb 24 '15 at 15:17

0 Answers0