Quiz 16 Solution

Challenge Problem: Deeper Understanding

Python's list.__contains__ method has semantics that check for whether any element of the list is equivalent to the given parameter. This can be demonstrated with the following experiment:

>>> x = list(range(5))
>>> y = list(range(5))
>>> id(x)
3695160
>>> id(y)
3689488
>>> x == y
True
>>> x is y		
False
>>> sample = [ x ]
>>> y in sample
True
Notice that the sample list has x as an element, yet it reports the distinct list y to be in the list, because y is equivalent to x. Had the semantics been looking for the precise identity, the last containment query would have returned False.

A simpler example can be constructed noting that floats and ints are distinct but can be equivalent, that is (4 == 4.0) is True yet (4 is 4.0) is False. We can then observe

>>> data = [4]
>>> 4.0 in data
True
and conclude that the containment check for lists suffices if it locates an equivalent element.


Last modified: Tuesday, 27 November 2018