Identity vs. Equality: basic-level questions

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]
______
>>> s is [1, 2, 3, 4]
______
>>> [1, 2, 3, 4] is [1, 2, 3, 4]
______
>>> a = s
>>> a is s
______
>>> a[1:] is s[1:]
______

Question 5

>>> s = (1, 2, 3, 4)
>>> s is (1, 2, 3, 4)
______
>>> s == [1, 2, 3, 4]
______
>>> 'hello' == 'hello'
______
>>> 'hello' is 'hello'
______