Introduction
Identity operators check if two things are actually the same object in memory, not just if they look the same.
Jump into concepts and practice - no test required
Identity operators check if two things are actually the same object in memory, not just if they look the same.
variable1 is variable2 variable1 is not variable2
is returns True if both variables point to the same object.
is not returns True if they point to different objects.
is returns True.a = [1, 2, 3] b = a print(a is b) # True
is returns False.a = [1, 2, 3] b = [1, 2, 3] print(a is b) # False
is to check if a variable is None.x = None print(x is None) # True
x and y are different objects, is not returns True.x = 5 y = 10 print(x is not y) # True
This program shows how is and is not work by comparing lists and checking for None.
a = [1, 2, 3] b = a c = [1, 2, 3] print('a is b:', a is b) print('a is c:', a is c) print('a is not c:', a is not c) x = None print('x is None:', x is None)
Use is only to check if two variables are the same object, not to compare values.
For value comparison, use == instead.
Checking for None should always use is None or is not None for clarity.
is checks if two variables point to the same object.
is not checks if they point to different objects.
Use these operators when object identity matters, like checking for None.
is operator check in Python?is operatoris operator checks whether two variables refer to the exact same object in memory.==, which checks if values are equal, is checks identity, meaning the same object.is checks object identity = C [OK]is means same object, not just equal value [OK]is with ==is checks value equalityis works like type comparisona is not the same object as b?is not.a is not b is the correct syntax; other options are either value comparison or invalid syntax.is not to check different objects, not != [OK]!= instead of is notnot is which is invalid!== in Pythonlist1 = [1, 2, 3] list2 = list1 list3 = [1, 2, 3] print(list1 is list2) print(list1 is list3)
list1 is list2list2 = list1, both point to the same object, so this is True.list1 is list3list3 is a new list with the same values but a different object, so this is False.is True; identical values but new object means False [OK]is with ==a = None
if a is not None:
print("Value exists")
else
print("No value")else line is missing a colon at the end, which is required in Python.is not with None is correct, and None is a keyword, so no quotes needed. Indentation looks fine.is not operatorx is exactly None before processing it. Which is the best way to do this?== and is for NoneNone is a singleton object in Python. The recommended way to check for it is using is because it checks identity.x is Noneif x is None: correctly checks if x points to the None object.is None to check for None [OK]is None to check for None [OK]== None instead of is Noneis not None when checking for None