Efficiently looping through lists in Python
<p>I need to make a python function which, given ordered list <code>a</code> and <code>b</code> returns <code>True</code> if there exists an item in a for which holds that there is an item in <code>b</code> that is <code>a+1</code>.</p>

<p>This is of course easily done by using something like this:</p>

<pre><code>for item in a:
  if (a+1 in b):
     return True
</code></pre>

<p>However, I need to make this as efficient as possible because the function will be used to process loads of data. The tip that was given me was to use the <code>iter()</code> and <code>next()</code> operations, but I have not found a way to use these for effecient processing yet. Does anyone know how to implement these, or use another fast algorythm?
Thanks in advance.</p>

<p>Thank you both for your answers! I ended up using a combined version of your solutions:</p>

<pre><code>a = iter(l1)
b = iter(l2)
i = next(a)
j = next(b)
try:
    while (i):
        if i + 1 == j:
            return True
        elif i + 1 &gt; j:
            j = next(b)
        else:
            i = next(a)
except StopIteration:
    return False
</code></pre>

python list loops iterator