python - subtracting ranges from bigger ranges
<p>The problem I have is that I basically would like to find if there are any free subnets between a BGP aggregate-address (ex: 10.76.32.0 255.255.240.0) and all the network commands on the same router (ex: 10.76.32.0 255.255.255.0, 10.76.33.0 255.255.255.0)</p>

<p>In the above example 10.76.34.0 -> 10.76.47.255 would be free.</p>

<p>I'm thinking of tackling this problem by converting the IP addresses and subnet masks to binary and subtracting that way.</p>

<p>To keep it simple I will keep this example in decimal but doing this would leave me with the following problem: let's say I have a range from 1 to 250, I subtract from this a smaller range that goes from 20 to 23, I would like to end up with a range from 1 to 19 and 24 to 250.</p>

<p>Using the range command doesn't really give me the expected results and while I could possibly create a list with every item in the range and subtract another list with a sub-set of items, it seems to me that it might not be a good idea to have lists with possibly tens of thousands of elements.</p>

<p>Hunor</p>

<p>If you are trying to create a "range" with a gap in it, i.e., with 1-9 and 24-250, you could try to use <a href="https://docs.python.org/3/library/itertools.html#itertools.filterfalse" rel="nofollow"><code>filterfalse</code></a> (or <a href="https://docs.python.org/2.7/library/itertools.html#itertools.ifilterfalse" rel="nofollow"><code>ifilterfalse</code></a> if you are using Python 2.X) from the <a href="https://docs.python.org/3/library/itertools.html#module-itertools" rel="nofollow"><code>itertools</code></a> module, which takes as its arguments a predicate and a sequence, and returns elements of the sequence where the predicate returns <code>False</code>. As an example, if you do:</p>

<pre><code>from itertools import filterfalse
new_range = filterfalse(lambda x: 20 &lt;= x &lt;= 23, range(1,251))
</code></pre>

<p><code>new_range</code> will be an iterable containing the numbers 1-19, and 24-250, which can be used similarly to <code>range()</code>:</p>

<pre><code>for i in new_range:
    do_things() 
</code></pre>

python networking range subnet