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>To get the smallest integer that is not a member of <code>vlans3</code>:</p>

<pre><code>ints_list = range(min(vlans3), max(vlans3) + 1)
missing_list = [x for x in ints_list if x not in vlans3]
first_missing = min(missing_list)
</code></pre>

<p>However you want to return 1 if the smallest value in your list is greater than 1, and the last value + 1 if there are no missing values, so this becomes:</p>

<pre><code>ints_list = [1] + list(range(min(vlan3), max(vlan3) + 2))
missing_list = [x for x in ints_list if x not in vlan3]
first_missing = min(missing_list)
</code></pre>

python python-3.x