0

When I run this as a file, it prints out True for both print statements.

a = 13579
b = 13579
print(a == b)
print(a is b)

But, it will show True and False if I run this in the Shell (I understand Python treats these two numbers as two objects); Where I got confused was why it shows True for both when running this as a Python file? Thank you!

kids.
  • 1
  • 1
    Have you read e.g. https://stackoverflow.com/q/43711154/3001761? – jonrsharpe Apr 09 '22 at 20:09
  • Also look at https://stackoverflow.com/questions/15171695/whats-with-the-integer-cache-maintained-by-the-interpreter . In short there is caching inside the interpreter for numbers between [-5,256], and then there is also constants caching for a parsed python file. When using a repl like IDLE, you lose the file caching, but will get it if you have block statements or do multiple assignments on a single line. For example, executing this as one line would typically print True, `a, b = 13579, 13579; print(a is b)` – flakes Apr 09 '22 at 20:14
  • @flakes Thank you! This cleared the confusions for me -- "there is also constants caching for a parsed python file". – kids. Apr 09 '22 at 20:20
  • Ah, the magic of the internal reuse of immutable objects. At least now you'll always remember that you should always use `==` to check for equality. Using `is` is for different purposes (and could an should be used if you compare something with `None`). – Matthias Apr 09 '22 at 20:41

0 Answers0