43

In Python, what is the efficiency of the in keyword, such as in:

a = [1, 2, 3]
if 4 in a:
  ...
1
  • How can a keyword be efficient? Commented Nov 14, 2016 at 9:53

2 Answers 2

56

The complexity for lists is:

O(n)

For sets it is:

O(1)

http://wiki.python.org/moin/TimeComplexity

Sign up to request clarification or add additional context in comments.

3 Comments

In general, but Felix Kling's answer is best. Someone could implement a MembershipList class which has a base list and also a membership set instance variable, and override __contains__ to check the set for O(1) time.
what about dictionaries @eduardo :)
44

It depends on the right hand operand:

The operators in and not in test for collection membership. [...] The collection membership test has traditionally been bound to sequences; an object is a member of a collection if the collection is a sequence and contains an element equal to that object. However, it make sense for many other object types to support membership tests without being a sequence. In particular, dictionaries (for keys) and sets support membership testing.

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.

The membership test operators (in and not in) are normally implemented as an iteration through a sequence. However, container objects can supply the following special method with a more efficient implementation, which also does not require the object be a sequence.


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

4 Comments

I suppose it will be the same for strings?
The collection membership test has traditionally been bound to sequences; Strings in python are sequences.
@Felix Kling If list is converted to a set before checking if element is part of it, will it be faster compared to checking directly in list?
@KocT9H: Depends on how often you do the check. If it's only once, then there will be no difference since, I assume, converting the the list to a set is also O(n).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.