0

I know '==' is used to check the equality of two values and 'is' is used to test the identity of objects in Python as pointed out in this post. However they can be both used for comparing numbers besides their other applications. I did some tests using both of them to compare two integers and 'is' appears to run faster. Why is that? and if that's true is there any other reason to use '==' for number comparisons at all?

timeit.timeit('1 is 1', number=10**8)
2.3460144830169156

timeit.timeit('1 == 1', number=10**8)
2.9029528259998187
Sajjad Bay
  • 197
  • 2
  • 9
  • 3
    Because `is` checks reference equality, which is basically comparing two integers (the references), but `==` typically takes a lot of comparisons, and possible casting, etc. – Willem Van Onsem Nov 14 '18 at 20:14
  • 4
    "However they can be both used for comparing numbers" - sure, if you want to perform a bizarre comparison that [**is not** an equality test](https://ideone.com/QRxKYT). – user2357112 Nov 14 '18 at 20:18
  • 2
    you cannot use it to check equal numbers with the exception of a handful of small numbers ...`x = 5000*2;print(x is 10000)` – Joran Beasley Nov 14 '18 at 20:21
  • 1
    Try assigning `x = 258` and `y = 258` (or larger numbers) on *separate* lines (not `x = 258; y = 258`, and then check the value of `x is y`. – chepner Nov 14 '18 at 20:25
  • 1
    @WillemVanOnsem: Correct, but pedantically, pointers are not integers. – Kevin Nov 14 '18 at 20:26
  • @chepner `257` will do :) – r.ook Nov 14 '18 at 20:35
  • @Idlehands Could have sworn 257 was in the list of interned ints for some reason. – chepner Nov 14 '18 at 20:38
  • Also `x = 1.0; x is 1.0` will fail miserably. – r.ook Nov 14 '18 at 20:38

0 Answers0