Will dwell on the search for alist on the element?
Yes, the in operator in the list performs a linear search with an early exit if the target is found. In addition, it will bypass the final comparison if the target object is identical to the object in the list.
Here's some trace code that proves the result by making comparisons visible:
class Int(int): 'Make comparisons visible' def __cmp__(self, other): print 'Comparing %s to %d' % (self, other) return int.__cmp__(self, other) ele1 = Int(1) ele2 = Int(2) ele3 = Int(3) ele4 = Int(4) ele5 = Int(5) alist = [ele1, ele2, ele3, ele4, ele5] if ele3 in alist: print "found"
Output:
Comparing 3 to 1 Comparing 3 to 2 found
Python converts the in operator in an ele3 in alist expression to a magic method call, such as alist.__contains__(ele3) . list .__ contains the __ () method , works as follows:
def __contains__(self, target): for element in self: if target is element or target == element: return True return False
We hope that the process is crystal clear :-)
source share