Python: find smallest missing positive integer in ordered list
<p>I need to find the first missing number in a list. If there is no number missing, the next number should be the last +1.</p>

<p>It should first check to see if the first number is > 1, and if so then the new number should be 1.</p>

<p>Here is what I tried. The problem is here: <code>if next_value - items &gt; 1:</code>
results in an error because at the end and in the beginning I have a <code>None</code>. </p>

<pre><code>list = [1,2,5]
vlans3=list

for items in vlans3:
    if items in vlans3:

        index = vlans3.index(items)
        previous_value = vlans3[index-1] if index -1 &gt; -1 else None
        next_value = vlans3[index+1] if index + 1 &lt; len(vlans3) else None
        first = vlans3[0]
        last = vlans3[-1]

                #print ("index: ", index)
        print ("prev item:", previous_value)
        print ("-cur item:", items)
        print ("nxt item:", next_value)

        #print ("_free: ", _free)
        #print ("...")
        if next_value - items &gt; 1:
            _free = previous_value + 1
            print ("free: ",_free)
            break

print ("**************")
print ("first item:", first)
print ("last item:", last)
print ("**************")
</code></pre>

<hr>

<p>Another method:</p>

<pre><code>L = vlans3

free = ([x + 1 for x, y in zip(L[:-1], L[1:]) if y - x &gt; 1][0])
</code></pre>

<p>results in a correct number if there is a gap between the numbers, but if no space left error occurs: <code>IndexError: list index out of range</code>. However I need to specify somehow that if there is no free space it should give a new number (last +1). But with the below code it gives an error and I do not know why.</p>

<pre><code>if free = []:
    print ("no free")
else:
    print ("free: ", free)
</code></pre>

<p>First avoid using reserved word <code>list</code> for variable.
Second use try:except to quickly and neatly avoid this kind of issues.</p>

<pre><code>def free(l):
    if l == []: return 0
    if l[0] &gt; 1: return 1
    if l[-1] - l[0] + 1 == len(l): return l[-1] + 1
    for i in range(len(l)):
        try:
            if l[i+1] - l[i] &gt; 1: break
        except IndexError:
            break
    return l[i] + 1
</code></pre>

python python-3.x