0

I know the time complexity of the 'in' operator for lists has a time complexity of O(n). I was wondering what the does code or logic for the operator looks like.

  • Well…you probably compare the first item of the sequence to the target, then the second, etc. until you find a match then stop and return True. If you get to the end without a match, you return False. This means that in the worst case you make `n` comparisons for a sequence with `n` items. – Mark Mar 01 '22 at 04:55
  • 2
    Maybe this will help: https://stackoverflow.com/questions/12244074/python-source-code-for-built-in-in-operator – Mark Mar 01 '22 at 05:00
  • In general, objects can define the ``__contains__(self, thing)`` method to implement a custom ``in`` test. However for the builtin objects (list, dict, set) it is probably hardcoded in C code. – Torben Klein Mar 01 '22 at 05:31
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Mar 01 '22 at 08:43

0 Answers0