Iterating through integers not found in a list of ranges in Python


So, I have a function which outputs a list of ranges, e.g. [range(1,5),range(8,13)]. I need to iterate through those integers which are not in a range in this list. For example, using the previous list I would like to be able to iterate through 5-7 in the previously mentioned list.

The lists and ranges i will be working with will likely be rather large (i.e. with integers ranging from 0 to many millions).

Is there any way to do this without converting each range to a list of numbers and using a if not in statement?


Using Mark’s template:

r = [range(1,5), range(8,13), range(20, 25), range(22, 27),  range(30, 35)]

def missing(r):
    stop = r[0].stop
    for a in r:
        yield from range(stop, a.start)
        stop = max(stop, a.stop)


[5, 6, 7, 13, 14, 15, 16, 17, 18, 19, 27, 28, 29]

Answered By – Kelly Bundy

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.