re: 3 Tricky Python Nuances VIEW POST


1) you should use a linter like pylint to avoid mistakes like this
2) is can be confusing for small integers because they share references
1 is 1 = True
158896587456 is 158896587456 = False


I tried 158896587456 is 158896587456 on Python 3.6.1 and it answers True :/
(Even with huge numbers it does answer True)


Sorry, this is true when (at least) one of them is stored into a variable:

>>> a = 1
>>> b = 1
>>> print(a is b)
>>> a = 123456789
>>> b = 123456789
>>> print(a is b)

Indeed ! But it's weird that 123456789 is 123456789 = True, isn't it ? As if Python answers True for a is b if "a is the same as b" before testing if they are the same. Is there a reason for that ?

(123456789+0) is 123456789 = False
but 123456789 is 123456789 = True

Anyway thanks for the example and the answer !

Optimizer gets better and better. In 3.7, even 123456788+1 is 123456789 gives True. It's simply that Python realizes it can evaluate constant pure expressions before compiling to bytecode. And it folds constants, of course.

>>> compile('123456788+1 is 123456789', '', 'eval').co_consts

You'll notice there's only one 123456789 there, not two. And there are no 123456788 nor 1.


1.) I mean. I almost always find “you should use a linter and then you can avoid learning” to be an unhelpful piece of advice. Also, a linter’s not going to tell you why a nested array is behaving unexpectedly.
2) And true. Python can definitely get a little weird around the edges when you get to arbitrarily large numbers. I hope you’re not hardcoding and checking for identity for integers like this in your code.

You clearly understand references very well! These short examples are, of course, aimed at introducing a concept and encouraging people to learn more. Thanks for providing some trivia!

code of conduct - report abuse