If you need help reviewing Identity vs. Equality, take a look at these resources:
Each question has a "Toggle Solution" button -- click it to reveal that question's solution.
Conceptual Questions
Question 1
What condition must be satisfied for the expression a is b
to be
True
?
a
and b
must reference the same physical object in memory.
Question 2
What special method determines if a == b
to be True
?
In each class, the __eq__
determines if two objects are equivalent
(but not identical). For user-defined types (i.e. classes), you can
implement your own __eq__
method! Otherwise, the default __eq__
for user-defined types behaves the same way as is
.
Question 3
For built-in types, if a is b
is True
, is a == b
guaranteed to be
True
?
Yes. in other words, a built-in object is, by definition, equivalent with itself. However, for user-defined types, you are able to break this property!
What would Python print?
Question 4
>>> s = [1, 2, 3, 4]
>>> s == [1, 2, 3, 4]
______True
>>> s is [1, 2, 3, 4]
______False
>>> [1, 2, 3, 4] is [1, 2, 3, 4]
______False # 2 separate objects in memory!
>>> a = s
>>> a is s
______True
>>> a[1:] is s[1:]
______False # slicing always creates new objects in memory
Question 5
>>> s = (1, 2, 3, 4)
>>> s is (1, 2, 3, 4)
______False # Immutability has nothing to do with identity
>>> s == [1, 2, 3, 4]
______False # a tuple cannot be equivalent to a list
>>> 'hello' == 'hello'
______True
>>> 'hello' is 'hello'
______True # strings are special -- Python only creates one copy of a string literal in memory