educative.io

Comparison operators

Hello,
when two variables have the same value, it seems that they refer to the same object
e.g.:
a = 10
b = 10
a is b #True
I read on the internet that this is only valid up to 256 and from 257 false
but in the Playground the value 1000 is still true.
But if I use Powershell and compare a and b with the is operator, it returns False from the value 257 (Python 3.11)

How does this make sense?

Kind regards


Course: https://www.educative.io/collection/10370001/5473789393502208
Lesson: https://www.educative.io/collection/page/10370001/5473789393502208/5429296082452480

Hi @Joachim_Bachmann !!
You are correct that in Python, for integer values outside of the range (-5 to 256), new objects are created in memory for each assignment and when we compare such variables with the same values, it returns true. This is because when we write the constant as part of our code, then it becomes part of our data and remains available for all variables using the value directly and it will return false only when we calculate a result of two variables to be the same, only then the rule of large integers (greater than 256) apply such as:

For example:

a,b = 100,199 
a += 100 b += 1
 print (a is b) # true 
a += 1 
b = 201 
print (a is b) # true
 a += 100
 b += 100
 print (a is b) # false
c=280
d=280
print(c is d)# True

I hope this helps. Happy Learning :blush:

1 Like