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?