-1

I am unable to figure out the output of the following program

big_num_1   = 1000
big_num_2   = 1000
small_num_1 = 1
small_num_2 = 1
big_num_1 is big_num_2 # False
small_num_1 is small_num_2 # True

What is happening above? Why is one False and other True.

Source: https://luminousmen.com/post/python-interview-questions-senior

frazman
  • 32,081
  • 75
  • 184
  • 269

1 Answers1

1

Because is compares the identity of two objects (that is, if they're exactly the same object.) You want to test for equality, and for that you must use the == operator:

big_num_1 == big_num_2
=> True

small_num_1 == small_num_2
=> True

In case you're wondering why this example worked:

small_num_1 is small_num_2
=> True

It's because Python caches small (between -5 and 256) int objects internally, so the objects used in the comparison were taken from the cache and were the same. big_num_1 and big_num_2 are greater than 256, so they're represented by two different objects, and the identity test fails.

Óscar López
  • 232,561
  • 37
  • 312
  • 386