6.7 Identity Operators

Identity Operators

The identity operators (is and is not) allow you to check if two variables are stored in the same location in memory. Take the code below:
message_1 = "hello" message_2 = "hello" print(message_1 is message_2) # True print(message_1 is not message_2) # False message_3 = "world" message_4 = "tahiti" print(message_3 is message_4) # False print(message_3 is not message_4) # True
View code on GitHub.
You might be wondering why we need the identity operators if we already have the equality operator (==). They seem like they're doing the same thing, right? Wrong. As mentioned above, the identity operators are used to check if two variables are stored in the same location in memory. For primitive data types such as strings or integers, if there are duplicate values, they are stored in the same location. However, for more "advanced" data types (which are called objects), this is not the case
# primitive values, if duplicated, are stored # in the same location x = 5 y = 5 if x is y: print("x is y") else: print("x is not y") # lists are objects, so they are located # in different locations in memory a = [1, 2, 3] b = [1, 2, 3] # use the identity operator to test if the 2 variables # reference the same location in memory if a is b: print("a is b") else: print("a is no b") # use the equality operator to test if the content # is equivalent if a == b: print("a == b") else: print("a != b")
View code on GitHub.
Output of the above code
x is y a is not b a == b
As you see, even though the lists a and b have the same content, because lists are objects, they are stored in different locations in memory. Thus, a is b returns False. On the other hand, a == b returns True because the content of the two lists are equal.
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.