3 ms·
My favorite example of something similar to this, since you brought it up: >>> a = [254, 255, 256, 257, 258] >>> b = [254, 255, 256, 257, 258] >>> for i
by cecilpl2 6y ago
My favorite example of something similar to this, since you brought it up:
>>> a = [254, 255, 256, 257, 258]
>>> b = [254, 255, 256, 257, 258]
>>> for i in range(5): print(a[i] is b[i])
...
True
True
True
False
False
In Python, integers in the range [-5, 256] are statically constructed in the interpreter and refer to fixed instances of objects. All other integers are created dynamically and refer to a new object each time they are created.
- mark-r 6y agoLeaky abstractions at its finest.
- sullyj3 6y agoI mean, people should be using `==` for this. The fact that `is` happens to work for small numbers is an implementation detail that shouldn't be relied upon.
- mark-r 6y agoAbsolutely. But because it does work they might start using it without knowing it's wrong, then be surprised when it doesn't work. Python has other areas where the common English definition of a word leads to misunderstandings about how they're to be used.
- kgm 6y agoThough "when" the object is created isn't always so straightforward: >>> x = 257 >>> y = 257 >>> x is y False >>> def f(): ... x = 257 ... y = 257 ... return x is y ... >>> f() True The lesson being that `is` is essentially meaningless for immutable objects, and to always use `==`.
- pansa2 6y ago> `is` is essentially meaningless for immutable objects OTOH it’s recommended to use `is` rather than `==` when comparing to “singletons like `None`”. https://www.python.org/dev/peps/pep-0008/#programming-recommendations https://www.python.org/dev/peps/pep-0008/#programming-recomm...
- joppy 6y agoWhat is the rationale behind this? '==' works all the time, and 'is' only works sometimes. Using 'is' wherever possible requires the user to know some rather arbitrary language details (which objects are singletons and which are not), wheras '==' will always give the correct answer regardless.
- pansa2 6y agoClasses can overload `==`: class C: def __eq__(self, other): return True print(C() == None) # True print(C() is None) # False