You can turn it into a recursive function:
def recursive_ranges(ranges):
if len(ranges) == 1:
return list(range(*ranges[0]))
else:
return list(range(*ranges[0])) + recursive_ranges(ranges[1:])
You can then call this, specifying ranges as a list of lists:
ranges = [[1, 4], [6, 11]]
recursive_ranges(ranges)
# [1, 2, 3, 6, 7, 8, 9, 10]
Note the *ranges[0]
is used to unpack the elements in ranges[0]
into individual arguments. Essentially the recursive function keeps grabbing the first element of ranges
, each element of which is a two-element array, and passing those numbers into the range()
method as two different values instead of one array. That's what the *
does, it unpacks the array. First call, you unpack [1, 4]
into range(1, 4)
and then append the next call of the recursive function to it.
Basically this unpacks into the following:
list(range(1, 4)) + list(range(6, 11))
but you get to use a much more compact syntax, just passing a list of lists.