Python List Operator Has Opportunity for Successful Search

If I have a list, then I am looking for an item in the list:

alist=[ele1, ele2, ele3, ele4,ele5,...] if ele3 in alist: print "found" 

Will dwell on the search for alist in ele3? Or it will work, although the entire remaining element is to the end.

Thanks in advance!

+6
source share
4 answers

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 :-)

+15
source

in stop searching the list when it finds the item.

A source

+2
source

Your goal of the condition is if ele3 in alist: check if ele3 exists in alist or not . Once it finds, then there is no need to process another element.

As if you had a condition

 False and True 

if the first element is False , then there is no need to process the rest statement. Because the rest of the statement will always be False .

The same rule applies to your state as soon as you find, then there is no need to process another element.

+1
source

Basically, the "In" operator works the same as this function:

 def IsInEnumerable(element, enumerable): for e in enumerable: if e == element: return True return False IsInEnumerable('test', ['foo', 'test', 'bar', 'meow', 'quack']) # True 

As you can see, there will be only two iterations of the 'for' loop. The same is true when using the in operator.

+1
source

Source: https://habr.com/ru/post/973393/


All Articles