Search code examples
pythonperformancelistmembership

Which is faster? Checking if something is in a Python list or not? I.e. membership vs non-membership


this might be a noob question or blindingly obvious to those who understand more computer science than I do. Perhaps that is why I could not find anything from Google or SO after some searching. Maybe I'm not using the right vocabulary.

The title says it all. If I know that x is in my_list most of the time, which of the following is faster?

if x in my_list:
    func1(x)
else:
    func2(x)

Or

if x not in my_list:
    func2(x)
else:
    func1(x)

Does the size of the list matter? E.g. ten elements vs 10,000 elements? For my particular case my_list consists of strings and integers, but does anyone have any idea if other considerations apply to more complicated types such as dicts?

Thank you.


Solution

  • Checking if element is in a list or if element is not in a list calling the same operation x in my_list, so there should not be any difference.

    Does the size of the list matter?

    Checking if element is in a list is an O(N) operation, this means that the size does matter, roughly proportionately.

    If you need to do checking a lot, you probably want to look into set, checking if an element is in a set is O(1), this means that checking time does not change much as size of set increases.