In Python, what is the efficiency of the in keyword, such as in:
a = [1, 2, 3]
if 4 in a:
...
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.
It depends on the right hand operand:
Classes can implement the special method
__contains__to override the default behavior (iterating over the sequence) and thus can provide a more (or less) efficient way to test membership than comparing every element of the container.Since you have a list in your example, it is iterated over and each element is compared until a match is found or the list is exhausted. The time complexity is usually
O(n).