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>Warning: not very well tested code. Assuming sorted lists as you wrote.</p>

<p>The idea behind the hint with <code>iter</code> and <code>next</code> is that within a single loop you can advance in one or in the other list. If the first number is too small, you try the next first number. If the second one is too small, you try the text second number.</p>

<pre><code>def test1(a, b): 
    ia = iter(a)
    ib = iter(b)
    try:
        ea = next(ia)
        eb = next(ib)
        while True:
            print("debug: comparing {} -- {}".format(ea, eb))
            diff = ea - eb
            if diff == -1: 
                print("debug: OK!")
                return True
            elif diff &lt; -1: 
                ea = next(ia)
            else:
                eb = next(ib)
    except StopIteration:
        print("debug: not found")
        return False

lista=[1,2,4,10,31,33,45,67]
listb=[7,16,22,29,34,39,49,59,60,100,200,300]
test1(lista, listb)
</code></pre>

<p>The the output shows the algorithm at work:</p>

<pre><code>debug: comparing 1 -- 7
debug: comparing 2 -- 7
debug: comparing 4 -- 7
debug: comparing 10 -- 7
debug: comparing 10 -- 16
debug: comparing 31 -- 16
debug: comparing 31 -- 22
debug: comparing 31 -- 29
debug: comparing 31 -- 34
debug: comparing 33 -- 34
debug: OK!
</code></pre>

python list loops iterator