Issue related to: Core Python – Equalities
Issue Link: https://www.reddit.com/r/learnpython/comments/fwhcas/whats_the_difference_between_and_is_not/
If I say
if x != 5:
if x is not 5:
is there a difference?
For this particular example, no there is no difference – the same output will be returned
However the reason why we have != and ‘is not’ is so that users can check whether python is comparing the values (!=) or whether Python is pointing to the same object in memory.
A good place to see this in action is in the following code:
list1 = ['a', 'b', 'c', 'b']list2 = ['a', 'b', 'c', 'b']print(list1 != list2)print(list1 is not list2)
The output is the following visualised:
The first print statement list1 != list2 checks to see if list1 and list2 have the same items inside if they do it will print False if they don’t it will print True. In this case they do have the same items so python will print False as seen on the first line of the print output.
The second print statement list1 is not list2 checks to see if the two lists are pointing to the same object in memory. If they are pointing to the same object in memory Python will print False otherwise if they are pointing to different objects it will print True. In this case Python is pointing at two different lists as shown in the picture.