Identity Operators
Identity operators don't ask whether two objects are equal. They ask whether both are really one and the same object, stored at the same memory location:
Identity Operators Table
main.py
# Operator | Description | Example
# is | Returns True if both variables are the same object | x is y
# is not | Returns True if both variables are not the same object | x is not y
Examples
Example
is gives True when two variables refer to one and the same object:
Prompt
Write a Python program that creates two lists with the same values, assigns one to a third variable, then uses the "is" operator to compare them and the "==" operator to check equality. Print the results.
Output: complete Python program
main.py
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z)
print(x is y)
print(x == y)
Example
is not gives True when two variables refer to different objects:
Prompt
Write a Python program that creates two lists with the same values and uses the "is not" operator to check if they are different objects. Print the result.
Output: complete Python program
main.py
x = ["apple", "banana"]
y = ["apple", "banana"]
print(x is not y)
Difference Between is and ==
== compares the values held by two variables, while is asks whether both variables refer to one object in memory.
Example
Prompt
Write a Python program that creates two lists with the same values and demonstrates the difference between "==" (value equality) and "is" (identity). Print the results.
Output: complete Python program
main.py
x = [1, 2, 3]
y = [1, 2, 3]
print(x == y)
print(x is y)