42

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

a = [1, 2, 3]
if 4 in a:
  ...
Ravindra S
  • 6,302
  • 12
  • 70
  • 108
John
  • 4,596
  • 11
  • 37
  • 43

2 Answers2

55

The complexity for lists is:

O(n)

For sets it is:

O(1)

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

Eduardo
  • 22,574
  • 11
  • 76
  • 94
  • 1
    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. – johannestaas Jun 06 '14 at 00:48
  • what about dictionaries @eduardo :) – PirateApp Apr 23 '18 at 04:26
  • [Implementation, where oneverify that it does, indeed, involve iterating](https://github.com/python/cpython/blob/main/Objects/listobject.c#L441-L454) – ijoseph Jun 22 '23 at 01:44
42

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 5
    I suppose it will be the same for strings? – Karol Dec 03 '12 at 21:44
  • 1
    `The collection membership test has traditionally been bound to sequences;` Strings in python are sequences. –  Jun 13 '13 at 21:02
  • @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 Dec 22 '20 at 08:40
  • 1
    @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)`. – Felix Kling Dec 22 '20 at 14:42