Concatenate multiple ranges in a list

Simplest way to do this is to call range() and unpack result inside list assignment.

x = [*range(1, 4), *range(6, 11)]

Alternatively you can use itertools.chain:

>>> import itertools
>>> list(itertools.chain(range(1, 5), range(20, 25)))
[1, 2, 3, 4, 20, 21, 22, 23, 24]

If numpy is an option, you can use np.r_ to concatenate slice objects:

import numpy as np

np.r_[1:4, 6:11]
# array([ 1,  2,  3,  6,  7,  8,  9, 10])

Tags:

Python