The “is” keyword allows us to compare the identities of two variables and returns True if they are the same, and False otherwise. To help fully grasp what this means, let’s refer back to something we’ve already learned about.
We have already seen how we can compare the values of two variables using the == operator:
name1 = "John"
name2 = "John"
if name1 == name2:
print("They share the same first name")
else:
print("They have different first names")
Take a look at the code below, which looks very similar to what we just did but assigns variables in a slightly different way:
price1 = 19.99
price2 = price1 # notice how we assign this value
if price1 == price2:
print("The items cost the same")
else:
print("The items have different costs")
Both of the above segments of code will return true when use the == operator, because both of their values are the same. However, depending on how we create the variables as seen in lines 1 and 2, their identities, or how they are referenced in memory, may differ. We can investigate this by using the id() attribute:
name1 = "John"
name2 = "John"
print(id(name1))
print(id(name2))
# the id's printed out should differ
price1 = 19.99
price2 = price1 # we alias the variables
print(id(price1))
print(id(price2))
# the variables are aliased together, so their id should be the same
When we create a variable by directly assigning it to another variable (like with price2), they are aliases, or refer to the same place in memory. This slight distinction has several implications, such as if we were to assign price1 the value 24.99 it would also assign this new value to price2 as well.
This idea of aliasing is evidenced when we use the keyword “is” to compare the identities of two variables. For example:
name1 = "John"
name2 = "John"
print(name1 is name2)
# False, because the variables have different identities
price1 = 19.99
price2 = price1
print(price1 is price2)
# True, because the variables are aliased and have the same identity
Containment in Python refers to the concept of checking whether a given object is present in a collection of objects, such as a list. This can be done using the in keyword.
For instance, if I wanted to determine if a given name is present in a roster of students, I could do the following:
students = ["Luke", "Leia", "Han", "Chewie", "Lando"]
if "Han" in students:
print("Han is in this class")
else:
print("Han is not in this class")
# the if-statement above is true
if "C3PO" in students:
print("C3PO is in this class")
else:
print("These are not the droids you're looking for")
# the if-statement above is false
The in keyword is a very quick and straightforward way to determine if a value is contained in a list, without having to perform a traversal.