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.
What condition must be satisfied for the expression
a is b to be
b must reference the same physical object in memory.
What special method determines if
a == b to be
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
for user-defined types behaves the same way as
For built-in types, if
a is b is
a == b guaranteed to be
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?
>>> 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
>>> 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