Skip to content

Equality, identity, and hashability [ref]

Problem

  • Compare two separately created [1, 2] lists for equality and identity.
  • Alias one list under two names and test identity.
  • Test whether x = None is the singleton None.
  • Use (1, 2) as a dictionary key.
  • Hash a plain class instance; demonstrate that a mutable list cannot be hashed.
  • Compute a hash-table bucket index for key "a" and capacity 8.

Python solution

a, b = [1, 2], [1, 2]
(a == b, a is b)  # (True, False)

a = [1, 2]
b = a
a is b  # True

x = None
x is None  # True

positions = {(1, 2): "cell"}
positions[(1, 2)]  # 'cell'

class Node:
    pass

isinstance(hash(Node()), int)  # True
try:
    hash([1, 2])
except TypeError:
    unhashable = True
unhashable  # True

hash("a") % 8 in range(8)  # True; hash values vary between processes