Computational biology PhD researcher. Interested in science, software development, and machine learning. I write about medical research at BioSky.co and contribute content to a variety of additional publications.CVAbout
One of the things that may seem confusing in Python is how there appears to be two ways to test if variables are the same: ‘==’ and ‘is’:
x = 200 y = 200 print(x == y) print(x is y)
Both comparison methods returned True, so they do the same thing right? Well, not really. To illustrate this, I’ll change the integer value assigned:
x = 500 y = 500 print(x == y) print(x is y)
Now we have ‘==’ returning True and ‘is’ returning False. What happened? Well, ‘==’ is referred to as the equality operator, and it checks that the values of the variables are the same. That’s why it returned True both times. On the other hand, ‘is’ is referred to as the identity operator and compares the id of the object that the variable points to. I have a more detailed post on object ids available here.
So the moral of this is that usually you just want to use the equality operator (‘==’), as there is no guarantee that variables storing the same number will also point to the same object (and therefore have the same object id). The only times you really need to use the ‘is’ operator is when you explicitly need to check if one variable is actually pointing to the same object as another variable.
Latest posts by Jack Simpson (see all)
- Fruit flies, honeybees, and alcohol - October 18, 2017
- I’m going to Silicon Valley! - October 15, 2017
- Sometimes working in the biology department is pretty neat - October 10, 2017