When using the ‘in’ operator to search for an item in a list e.g.
if item in list:
print item
What algorithm is used to search for this item. Is it a straight search of the list from beginning to end or does it use something like binary search?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
lists can’t be assumed to be in sorted order (or any order at all), so binary search won’t work. Nor can the keys be assumed to be hashable, so unlike adictorseta hash-table lookup can’t be used to accelerate the searchAt a guess it’s a straight-through check of every element from first to last.
I’ll try and dig up the relevant Python source code.
—
Edit: The Python
list.__contains__()function, which implements theinoperator, is defined in listobject.c:It iterates over every element in the list, from the first element to the last element (or until it finds a match.) No shortcuts here.
—
Edit 2: The plot thickens. If Python detects that you’re testing for membership of an element in a constant
listorset, like:Edit 3 [@JohnMachin]:
The constant list is optimised to a constant tuple in 2.5-2.7 and 3.1-3.3.
The constant set is optimised to a (constant) frozenset in 3.3.
See also @CoryCarson’s answer.