0

I'm trying to understand what is going on under the hood a bit more in Python. I have two snippets of code, each having list1 and list2 as variables containing a list of integers:

Snippet 1:

for x in list1:
    for y in list2:
        if x == y: True

Snippet 2:

for y in list2:
    if y in list1: True

Both of them compare list 1 and list 2 and tell us whether they have anything in common, but snippet 2 executes about twice as fast as snippet 1, and I am trying to understand why.

What is actually going on when using if y in list, which examines each element and determines if they match, as opposed to looping through each element for comparison, that makes it so much faster?

smpat04
  • 57
  • 7
  • 2
    The difference is just that one of the loops is in optimized C/C++ code, the other is done by interpreting Python. – Barmar Oct 04 '20 at 05:44
  • Is `True` supposed to be `return True`? Of not, neither loop actually tells you whether they found a match. – Barmar Oct 04 '20 at 05:46
  • And the loop doesn't stop when it finds a match. – Barmar Oct 04 '20 at 05:46
  • 2
    Does this answer your question? [Python == with or vs. in list comparison](https://stackoverflow.com/questions/50877313/python-with-or-vs-in-list-comparison) – Omar Al-Howeiti Oct 04 '20 at 05:48
  • The code itself is designed to evaluate every value in both lists, which would be the worst-case scenario. I think Omar's response is what I was looking for- I don't know why I couldn't find it when I searched. Thanks for the responses! – smpat04 Oct 04 '20 at 13:41

0 Answers0